From 7ac68dfb7b9477269e1204b246e7827baec79274 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 06:59:53 +1300 Subject: [PATCH 01/39] Quarantine retained actor identity and add exact namespace-qualified storage lookup --- .../entity-management-service/README.md | 4 +- .../api-contracts.md | 2 + .../runtime-and-data.md | 10 +- .../gameplay-rules-entities-and-effects.md | 8 +- .../entity/ActorIdentity.java | 74 ++ .../entity/ActorIdentityStatus.java | 6 + .../entitymanagement/entity/Character.java | 1 + .../mapper/CharacterMapper.java | 1 + .../ActorActiveConditionRepository.java | 34 +- .../repository/ActorIdentityRepository.java | 109 +++ .../ActorResourceStateRepository.java | 29 +- .../CharacterEquipmentRepository.java | 6 +- .../repository/CharacterFriendRepository.java | 48 +- .../repository/CharacterRepository.java | 104 ++- .../QuarantinedActorRetentionRepository.java | 82 ++ .../service/ScopedCharacterResolver.java | 24 +- .../service/impl/CharacterServiceImpl.java | 58 +- .../EntityUpgradeValidationServiceImpl.java | 13 +- .../RuntimeInstanceCleanupServiceImpl.java | 11 +- ...__quarantine_unresolved_actor_identity.sql | 157 ++++ ...tainerInstanceLocationIntegrationTest.java | 46 + .../RetainedActorIdentityIntegrationTest.java | 846 ++++++++++++++++++ .../entity/ActorIdentityValueTest.java | 108 +++ .../service/ScopedCharacterResolverTest.java | 48 + .../impl/CharacterServiceImplListTest.java | 46 +- .../impl/CharacterServiceImplTest.java | 45 +- .../impl/ContainerServiceImplTest.java | 47 +- .../impl/EquipmentServiceImplTest.java | 49 +- .../service/impl/FriendServiceImplTest.java | 27 +- .../impl/InventoryServiceImplTest.java | 35 +- 30 files changed, 1890 insertions(+), 188 deletions(-) create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index ee6c681fd2..7a8d74b6e3 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,9 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Persisted rows and realm-aware listing exist, but synthetic-ID paths, fixed RPG columns, published entry-policy/descriptor/template resolution, policy-specific roster handling, namespace-idempotent auto-provision, and fork-local copy proof remain gaps. +V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. V1 rows and rows created through legacy numeric-ID paths are `QUARANTINED` unless an exact Account UUID plus Game Design-owner-resolved tenant UUID, namespace, and immutable scope are present; the old numeric `account_id`/`tenant_id` and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output is implemented, but Entity's trusted receiving and actor-provenance binding path is absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. There is no mapping or promotion operation and no canonical roster or PLAY activation. Legacy gameplay roster/name lookups return no actors, actor graph reads bypass stale cache entries and recheck persisted disposition, and the exact UUID-qualified repository lookup is not wired as a runtime admission path. Production scoped inventory, containment, equipment, and actor-state/effect calls still fail closed for legacy actor identities; the conditional service and persistence tests do not establish owner-qualified gameplay admission. Synthetic-ID paths, fixed RPG columns, published entry-policy/descriptor/template resolution, namespace-idempotent auto-provision, and fork-local copy proof remain gaps. + +The focused SQL-isolation fixtures may insert owner-resolved rows to test exact tenant/account/namespace/scope predicates; those rows are fixture evidence only and do not prove an Account or Game Design owner supplied that provenance at runtime. Existing `shared-live`, `instance:`, numeric Account/tenant IDs, names, caller checksums, and Game Session pointers never fill missing UUID provenance. World-owned `character_location` and `npc_location` tables, together with their authoritative movement, occupancy, and read paths, are target-only. They are absent from the current schema and runtime; current room topology or session bindings do not establish location authority, and Entity Management must not persist a competing location table, field, or cache authority. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index a592a0d3cf..5fab3c3a8f 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -10,6 +10,8 @@ The live crafting REST surface is runtime-reachable but is not a tenant-authoriz The live `CharacterController`, `InventoryController`, `EquipmentController`, and `FriendController` REST handlers are also legacy direct adapters. They remain runtime-reachable behind baseline bearer authentication and their implemented tenant-access checks. +Entity V2 now gives persisted characters a private opaque UUID, but the existing REST/gRPC numeric character identifiers are not aliases for that UUID. Legacy actor creation stores the numeric fields and key as source evidence and leaves the actor quarantined; legacy gameplay roster/name reads fail closed, and scoped gameplay access requires a persisted owner-resolved disposition. No public mapping/resolution RPC or account/tenant/namespace provenance producer is defined by this slice. Account UUID and Game Design-owned tenant UUID/namespace/scope must arrive as owner-backed evidence before canonical roster or PLAY can open. A fixture-created owner-resolved row demonstrates repository SQL isolation only, not runtime ownership proof. + Target crafting REST behavior is an authenticated, tenant-scoped design-time surface (not a player crafting shortcut). Entity must derive or validate the target tenant from the authenticated `SessionContext`, reject a caller-supplied tenant that is absent or different from that context, and use tenant-qualified recipe predicates for every read and update. Result and ingredient item references must resolve to items owned by that same tenant and applicable Draft/version scope before persistence; a recipe, result item, or ingredient from another tenant must fail closed without changing recipe or ingredient rows. The focused proof must cover missing/invalid context, tenant A requesting or updating tenant B's recipe, and tenant A attempting to reference tenant B's result or ingredient item. `ApplyActorCondition` has not yet converged on the target replay contract below. Its current request has no dedicated `effectId`; Game Session places the operation-unique durable effect ID in required `sourceId`, which Entity Management first uses as the `{tenantId, effectId}` key for its durable replay marker and operation-name check. The first application then separately uses the first active-condition row matching `{tenantId, playableStateKey, characterId, sourceType, sourceId}`; that narrower lookup does not compare the complete condition payload on same-operation reuse. Until migration, current `sourceId` values must therefore be unique tenant-wide per intended operation/effect, even though the actor-condition row lookup has the narrower scope. This temporary implementation conflates replay identity with authored/source provenance. The current request also accepts caller-supplied `effectPayloadJson`; because `QueryActorState` currently evaluates persisted condition payloads into gameplay-visible actor state, callers must not treat that caller-supplied payload or payload-driven state as trusted typed-effect authority; the transitional evaluation remains until the target server-resolved typed effect snapshot is persisted and read. This is a transitional implementation gap, not mutation authority. The proto, callers, persistence, and proof must migrate together before additional producers reuse one source across applications. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index b9eaa2b9eb..ae8cbac8ec 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,12 +13,14 @@ This document defines Entity Management’s runtime model, persistence ownership - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. -- The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for rows whose `expires_at` has elapsed, without tenant/namespace/instance predicates or a batch bound. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. +- The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. -- The live runtime-instance cleanup path currently deletes room-ground inventory, item stacks, item instances, and container instances by `(tenantId, gameInstanceId)` alone. It does not apply namespace, scope, and holder/container closure or prove S3 classification, so its cleanup acknowledgement is unsafe for replacement until owner-local classification, fencing, and focused proof are complete. -- The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. +- Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. +- Legacy character roster/name reads return no actors, numeric-ID graph reads require a fresh persisted `OWNER_RESOLVED` row and bypass the old character graph cache, and scoped gameplay resolution fails closed instead of translating `shared-live` or `instance:`. Consequently, production scoped inventory, containment, equipment, friend, and actor-state/effect calls do not admit legacy actor identities; no canonical owner-qualified gameplay admission path is connected. Resource/condition repositories additionally gate retained rows by actor disposition, and quarantined conditions are excluded from expiry. Conditional service and holder-persistence tests exercise downstream behavior only after an explicitly mocked test guard and do not prove owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. +- Runtime-instance cleanup now refuses to acknowledge cleanup while the target `(tenantId, gameInstanceId)` still contains item instances, containers, stacks, or room-ground rows, because those legacy families lack owner-resolved namespace/scope classification and may not be assumed S3. A quarantined-actor-linked transfer audit also holds cleanup. The check covers the actual target runtime holder set and its nested closure; it does not infer a character association from the runtime pointer, relabel room-ground rows, or delete audits/replay receipts. Empty-target cleanup does not establish that nonempty legacy families are safe to dispose. +- `characters` still retains the legacy private numeric account/tenant IDs and `playable_state_key`; only the canonical actor provenance columns are UUID-shaped. `actor_resource_states` also retains legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and holder/containment rows do not yet carry `playableStateNamespaceId` (and some omit `tenant_id`). Those dependent families therefore do not yet enforce target `{tenantUuid, playableStateNamespaceId, domainObjectId}` identity. V2 preserves them without inferred mapping; canonical dependent-row migration and owner-backed namespace isolation remain open. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. -- The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. +- `getWithInventory(characterId)` no longer reads from or populates the legacy `characterGraph` cache; it always performs a fresh persisted `OWNER_RESOLVED` read, so stale cache entries cannot authorize a response. The old ID-only cache has no namespace or authoritative-version validation and must not be reconnected as correctness authority; the target namespace-qualified Class A `character-cache:*` contract remains unimplemented. - `EntityDraftDesignDigestServiceImpl` currently emits `digestSchemaVersion=1` without hashing item `equipmentSlotGroupKey`, while `EquipmentServiceImpl` uses that field for slot compatibility admission. The digest is therefore incomplete for equipment semantics: different slot-group constraints may attest the same content digest. Target convergence adds the normalized field, bumps the schema version, and proves cross-version digest isolation plus publish-gate rejection of a changed constraint. ## Architecture and Design Notes diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 9658bd53ef..7b07280f43 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,10 +26,10 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - durable character, NPC, and item records plus bounded XP and NPC respawn-eligibility checks exist; Entity is the target persisted actor owner, but policy-aware entry, unified actor runtime, and complete respawn lifecycle do not. | `proven` - focused character, NPC, and item/inventory tests cover bounded records and lifecycle seams, not PLAYER-01 policy/copy proof. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Synthetic-ID risk, fixed RPG-shaped fields, published policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain unproven. | -| GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | -| GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | -| GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `partial` - `ActorIdentityValueTest` passed 3/3; `RetainedActorIdentityIntegrationTest` compiled but all 4 PostgreSQL-backed cases were skipped because Docker is unavailable. The migration/SQL-isolation assertions are authored, not executed; fixture-created `OWNER_RESOLVED` rows prove SQL predicates only, not owner-backed runtime provenance. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | +| GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `partial` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | +| GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `partial` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | +| GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `partial` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | | GR-4.2 Combat and conflict resolution | `not-implemented` - no combat/conflict resolver or authoritative combat loop is present. | `audited` - adjacent action-state/effect tests were inspected, but no focused combat proof exists. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md) | No production anchor: no combat owner is implemented. Adjacent context only: [ActionStateCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) and [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java) are non-combat seams. | No focused executable proof. [ActionStateCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java) is legacy context for the removed transient action-state handler path, not current combat proof; this does not mean the live durable `BLOCK` gameplay command or its replay-record category was removed. | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [GR-1.2](./game-session-runtime-and-tick-coordination.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Damage packets, hit/mitigation ordering, combat timing, body-region resolution, and combat-driven defeat/loot/revival/victory behavior remain absent. | | GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads are live; ability and skill progression is not. | `proven` - focused character progression and actor-state tests cover the bounded XP/level seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | | GR-4.4 In-game economy, trading, crafting, and exchange | `partial` - version-scoped recipe/ingredient persistence and CRUD APIs exist; gameplay crafting, economy, trading, and exchange do not. | `proven` - focused crafting controller/service tests cover recipe persistence and validation; item transfer tests cover only the adjacent substrate. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Entity API current status](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status) | [CraftingServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImpl.java); [CraftingController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java); [CraftingRecipe.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CraftingRecipe.java); [crafting schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [CraftingServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImplTest.java); [CraftingControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Material consumption/result creation, currency and vendor policy, trade/exchange flows, and end-to-end player proof remain absent. | diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java new file mode 100644 index 0000000000..564ea95722 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.entitymanagement.entity; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.util.StringUtils; + +/** Canonical Entity-owned actor identity and the provenance disposition that gates its use. */ +public record ActorIdentity( + UUID characterUuid, + UUID accountUuid, + UUID tenantUuid, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + ActorIdentityStatus status, + String quarantineReason) { + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String UUID_PATTERN = + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; + + public ActorIdentity { + requireNonNil(characterUuid, "characterUuid"); + requireNonNilWhenPresent(accountUuid, "accountUuid"); + requireNonNilWhenPresent(tenantUuid, "tenantUuid"); + requireNonNilWhenPresent(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(status, "status"); + if (playableStateScope != null) { + requireScope(playableStateScope); + } + if (status == ActorIdentityStatus.OWNER_RESOLVED) { + requireNonNil(accountUuid, "accountUuid"); + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireScope(playableStateScope); + if (StringUtils.hasText(quarantineReason)) { + throw new IllegalArgumentException( + "owner-resolved identity cannot have a quarantine reason"); + } + } else if (!StringUtils.hasText(quarantineReason)) { + throw new IllegalArgumentException("quarantined identity requires a reason"); + } + } + + public static UUID parseRequiredUuid(String value, String fieldName) { + if (!StringUtils.hasText(value) || !value.matches(UUID_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID"); + } + UUID parsed = UUID.fromString(value); + requireNonNil(parsed, fieldName); + return parsed; + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static void requireNonNilWhenPresent(UUID value, String fieldName) { + if (value != null && NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must not be the nil UUID"); + } + } + + public static PlayableStateScope requireScope(PlayableStateScope scope) { + if (scope == null + || (scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) { + throw new IllegalArgumentException("playableStateScope must be owner-resolved"); + } + return scope; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java new file mode 100644 index 0000000000..67bcce21ee --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.entitymanagement.entity; + +public enum ActorIdentityStatus { + OWNER_RESOLVED, + QUARANTINED +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java index 935b98a45c..9056764770 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java @@ -11,6 +11,7 @@ @EqualsAndHashCode(onlyExplicitlyIncluded = true) public class Character { @EqualsAndHashCode.Include private Long id; + private ActorIdentity actorIdentity; private Long tenantId; private Long accountId; private String playableStateKey; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java index 80f448eb72..4187236beb 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java @@ -14,6 +14,7 @@ public interface CharacterMapper { @Mapping(target = "lastLoginAt", ignore = true) @Mapping(target = "playableStateKey", ignore = true) @Mapping(target = "bodyLayoutKey", constant = "DEFAULT") + @Mapping(target = "actorIdentity", ignore = true) @Mapping(target = "version", ignore = true) Character toEntity(CharacterDto dto); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java index bc84020bf9..6863e9ed80 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java @@ -2,6 +2,7 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; import static net.firedevops.firemud.entitymanagement.jooq.Tables.ACTOR_ACTIVE_CONDITIONS; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; @@ -10,6 +11,7 @@ import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -32,6 +34,7 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) + .and(ownerResolvedActorExists()) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -59,6 +62,7 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) + .and(ownerResolvedActorExists()) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) @@ -67,6 +71,7 @@ public List findActiveForCharacter( } public ActorActiveCondition save(ActorActiveCondition entity) { + requireOwnerResolvedActor(entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_ACTIVE_CONDITIONS) @@ -109,10 +114,37 @@ public int deleteExpired(Instant now) { ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT .isNotNull() - .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now)))) + .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now))) + .and(ownerResolvedActorExists())) .execute(); } + private org.jooq.Condition ownerResolvedActorExists() { + return DSL.exists( + dsl.selectOne() + .from(CHARACTERS) + .where( + CHARACTERS + .ID + .eq(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID) + .and(CHARACTERS.TENANT_ID.eq(ACTOR_ACTIVE_CONDITIONS.TENANT_ID)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + } + + private void requireOwnerResolvedActor(Long tenantId, Long characterId) { + long ownerResolvedCount = + dsl.fetchCount( + CHARACTERS, + CHARACTERS + .ID + .eq(characterId) + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); + if (ownerResolvedCount != 1) { + throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + } + } + private ActorActiveCondition toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java new file mode 100644 index 0000000000..1d2eca7ecb --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** + * Exact, uncached canonical actor lookup. It intentionally has no write or resolution operation. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class ActorIdentityRepository { + private final DSLContext dsl; + + public ActorIdentityRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public List findOwnerResolvedRoster( + String tenantUuid, + String accountUuid, + String playableStateNamespaceId, + PlayableStateScope playableStateScope) { + UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); + UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); + UUID namespace = + ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); + if (scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) { + throw new IllegalArgumentException("playableStateScope is not a supported resolved scope"); + } + return dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) + .from(CHARACTERS) + .where( + CHARACTERS + .ACTOR_IDENTITY_STATUS + .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.eq(tenant)) + .and(CHARACTERS.ACCOUNT_UUID.eq(account)) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name()))) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .fetch(this::toIdentity); + } + + public Optional findOwnerResolvedActor( + String tenantUuid, + String accountUuid, + String playableStateNamespaceId, + PlayableStateScope playableStateScope, + String characterUuid) { + UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); + UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); + UUID namespace = + ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); + UUID requestedCharacter = ActorIdentity.parseRequiredUuid(characterUuid, "characterUuid"); + return Optional.ofNullable( + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) + .from(CHARACTERS) + .where( + CHARACTERS + .ACTOR_IDENTITY_STATUS + .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.eq(tenant)) + .and(CHARACTERS.ACCOUNT_UUID.eq(account)) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name())) + .and(CHARACTERS.CHARACTER_UUID.eq(requestedCharacter))) + .fetchOne(this::toIdentity)); + } + + private ActorIdentity toIdentity(Record record) { + return new ActorIdentity( + record.get(CHARACTERS.CHARACTER_UUID), + record.get(CHARACTERS.ACCOUNT_UUID), + record.get(CHARACTERS.TENANT_UUID), + record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), + PlayableStateScope.valueOf(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), + ActorIdentityStatus.valueOf(record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), + record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON)); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 478bd81341..2c7064cecd 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java @@ -2,12 +2,14 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; import static net.firedevops.firemud.entitymanagement.jooq.Tables.ACTOR_RESOURCE_STATES; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -29,12 +31,23 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO .TENANT_ID .eq(tenantId) .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId))) + .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId)) + .and( + DSL.exists( + dsl.selectOne() + .from(CHARACTERS) + .where( + CHARACTERS + .ID + .eq(ACTOR_RESOURCE_STATES.CHARACTER_ID) + .and(CHARACTERS.TENANT_ID.eq(ACTOR_RESOURCE_STATES.TENANT_ID)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } public ActorResourceState save(ActorResourceState entity) { + requireOwnerResolvedActor(entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_RESOURCE_STATES) @@ -68,6 +81,20 @@ public ActorResourceState save(ActorResourceState entity) { return entity; } + private void requireOwnerResolvedActor(Long tenantId, Long characterId) { + long ownerResolvedCount = + dsl.fetchCount( + CHARACTERS, + CHARACTERS + .ID + .eq(characterId) + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); + if (ownerResolvedCount != 1) { + throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + } + } + private ActorResourceState toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java index acfd6bd865..c8caf02fd4 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java @@ -35,7 +35,8 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)))); + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); var content = dsl.select( CHARACTER_EQUIPMENT.CHARACTER_ID, @@ -68,7 +69,8 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId))) + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) .orderBy(CHARACTER_EQUIPMENT.SLOT.asc()) .limit( JooqEntityManagementRepositorySupport.limitOrDefault(pageable, Integer.MAX_VALUE)) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java index a206dbbc9a..af5a062bac 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.entitymanagement.repository; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTER_FRIEND; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -9,6 +10,7 @@ import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @@ -25,10 +27,11 @@ public CharacterFriendRepository(DSLContext dsl) { } public Page findByIdCharacterId(Long characterId, Pageable pageable) { - long total = dsl.fetchCount(CHARACTER_FRIEND, CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)); + var condition = CHARACTER_FRIEND.CHARACTER_ID.eq(characterId).and(ownerResolvedPair()); + long total = dsl.fetchCount(CHARACTER_FRIEND, condition); var content = dsl.selectFrom(CHARACTER_FRIEND) - .where(CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)) + .where(condition) .orderBy(CHARACTER_FRIEND.FRIEND_ID.asc()) .limit(limitOrDefault(pageable, Integer.MAX_VALUE)) .offset(offsetOrZero(pageable)) @@ -47,11 +50,23 @@ public Optional findById(CharacterFriendKey key) { CHARACTER_FRIEND .CHARACTER_ID .eq(key.getCharacterId()) - .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId()))) + .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId())) + .and(ownerResolvedPair())) .fetchOne(this::toEntity)); } public CharacterFriend save(CharacterFriend entity) { + long ownerResolvedCount = + dsl.fetchCount( + CHARACTERS, + CHARACTERS + .ID + .in(entity.getId().getCharacterId(), entity.getId().getFriendId()) + .and(CHARACTERS.TENANT_ID.eq(entity.getTenantId())) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); + if (ownerResolvedCount != 2) { + throw new IllegalStateException("FRIEND_ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + } if (findById(entity.getId()).isEmpty()) { dsl.insertInto(CHARACTER_FRIEND) .set(CHARACTER_FRIEND.CHARACTER_ID, entity.getId().getCharacterId()) @@ -69,10 +84,35 @@ public void deleteById(CharacterFriendKey key) { CHARACTER_FRIEND .CHARACTER_ID .eq(key.getCharacterId()) - .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId()))) + .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId())) + .and(ownerResolvedPair())) .execute(); } + private org.jooq.Condition ownerResolvedPair() { + var ownerResolvedCharacter = + DSL.exists( + dsl.selectOne() + .from(CHARACTERS) + .where( + CHARACTERS + .ID + .eq(CHARACTER_FRIEND.CHARACTER_ID) + .and(CHARACTERS.TENANT_ID.eq(CHARACTER_FRIEND.TENANT_ID)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + var ownerResolvedFriend = + DSL.exists( + dsl.selectOne() + .from(CHARACTERS) + .where( + CHARACTERS + .ID + .eq(CHARACTER_FRIEND.FRIEND_ID) + .and(CHARACTERS.TENANT_ID.eq(CHARACTER_FRIEND.TENANT_ID)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + return ownerResolvedCharacter.and(ownerResolvedFriend); + } + private CharacterFriend toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 9e2d219ee4..68ea9493f0 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -8,6 +8,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.LinkedHashSet; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.InventoryEntry; import net.firedevops.firemud.entitymanagement.entity.InventoryKey; @@ -32,7 +33,9 @@ public CharacterRepository(DSLContext dsl) { public Optional findWithInventoryById(Long id) { Character character = - dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity); + dsl.selectFrom(CHARACTERS) + .where(CHARACTERS.ID.eq(id).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .fetchOne(this::toEntity); if (character == null) { return Optional.empty(); } @@ -65,13 +68,20 @@ public Optional findWithInventoryById(Long id) { public Optional findById(Long id) { return Optional.ofNullable( - dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity)); + dsl.selectFrom(CHARACTERS) + .where(CHARACTERS.ID.eq(id).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .fetchOne(this::toEntity)); } public Optional findByIdAndTenantId(Long id, Long tenantId) { return Optional.ofNullable( dsl.selectFrom(CHARACTERS) - .where(CHARACTERS.ID.eq(id).and(CHARACTERS.TENANT_ID.eq(tenantId))) + .where( + CHARACTERS + .ID + .eq(id) + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) .fetchOne(this::toEntity)); } @@ -84,7 +94,8 @@ public Optional findByIdAndTenantIdAndPlayableStateKey( .ID .eq(id) .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey))) + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) .fetchOne(this::toEntity)); } @@ -95,7 +106,8 @@ public Page findByTenantIdAndAccountIdAndPlayableStateKey( .TENANT_ID .eq(tenantId) .and(CHARACTERS.ACCOUNT_ID.eq(accountId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)); + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")); long total = dsl.fetchCount(CHARACTERS, condition); var content = dsl.selectFrom(CHARACTERS) @@ -118,7 +130,8 @@ public Optional findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( .TENANT_ID .eq(tenantId) .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase()))) + .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase())) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) .limit(1) .fetchOne(this::toEntity)); } @@ -127,10 +140,20 @@ public long countByTenantId(Long tenantId) { return dsl.fetchCount(CHARACTERS, CHARACTERS.TENANT_ID.eq(tenantId)); } + public long countQuarantinedByTenantId(Long tenantId) { + return dsl.fetchCount( + CHARACTERS, + CHARACTERS.TENANT_ID.eq(tenantId).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("QUARANTINED"))); + } + public Character save(Character entity) { if (entity.getId() == null) { + UUID characterUuid = UUID.randomUUID(); Long id = dsl.insertInto(CHARACTERS) + .set(CHARACTERS.CHARACTER_UUID, characterUuid) + .set(CHARACTERS.ACTOR_IDENTITY_STATUS, "QUARANTINED") + .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, "OWNER_PROVENANCE_MISSING") .set(CHARACTERS.TENANT_ID, entity.getTenantId()) .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) @@ -148,27 +171,35 @@ public Character save(Character entity) { .set(CHARACTERS.VERSION, entity.getVersion()) .returningResult(CHARACTERS.ID) .fetchOne(CHARACTERS.ID); - return findById(id).orElseThrow(); + return findStoredById(id).orElseThrow(); + } + int updatedRows = + dsl.update(CHARACTERS) + .set(CHARACTERS.TENANT_ID, entity.getTenantId()) + .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) + .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) + .set(CHARACTERS.NAME, entity.getName()) + .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) + .set(CHARACTERS.LEVEL, entity.getLevel()) + .set(CHARACTERS.EXPERIENCE, entity.getExperience()) + .set(CHARACTERS.STRENGTH, entity.getStrength()) + .set(CHARACTERS.AGILITY, entity.getAgility()) + .set(CHARACTERS.INTELLIGENCE, entity.getIntelligence()) + .set(CHARACTERS.STAMINA, entity.getStamina()) + .set(CHARACTERS.HEALTH, entity.getHealth()) + .set(CHARACTERS.MANA, entity.getMana()) + .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) + .set(CHARACTERS.LAST_LOGIN_AT, toLocalDateTime(entity.getLastLoginAt())) + .set(CHARACTERS.VERSION, entity.getVersion() + 1) + .where( + CHARACTERS + .ID + .eq(entity.getId()) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .execute(); + if (updatedRows != 1) { + throw new IllegalStateException("CHARACTER_IDENTITY_NOT_OWNER_RESOLVED"); } - dsl.update(CHARACTERS) - .set(CHARACTERS.TENANT_ID, entity.getTenantId()) - .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) - .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) - .set(CHARACTERS.NAME, entity.getName()) - .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) - .set(CHARACTERS.LEVEL, entity.getLevel()) - .set(CHARACTERS.EXPERIENCE, entity.getExperience()) - .set(CHARACTERS.STRENGTH, entity.getStrength()) - .set(CHARACTERS.AGILITY, entity.getAgility()) - .set(CHARACTERS.INTELLIGENCE, entity.getIntelligence()) - .set(CHARACTERS.STAMINA, entity.getStamina()) - .set(CHARACTERS.HEALTH, entity.getHealth()) - .set(CHARACTERS.MANA, entity.getMana()) - .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) - .set(CHARACTERS.LAST_LOGIN_AT, toLocalDateTime(entity.getLastLoginAt())) - .set(CHARACTERS.VERSION, entity.getVersion() + 1) - .where(CHARACTERS.ID.eq(entity.getId())) - .execute(); return findById(entity.getId()).orElseThrow(); } @@ -178,6 +209,16 @@ private Character toEntity(Record record) { } Character character = new Character(); character.setId(record.get(CHARACTERS.ID)); + character.setActorIdentity( + new net.firedevops.firemud.entitymanagement.entity.ActorIdentity( + record.get(CHARACTERS.CHARACTER_UUID), + record.get(CHARACTERS.ACCOUNT_UUID), + record.get(CHARACTERS.TENANT_UUID), + record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), + scopeFrom(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), + net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus.valueOf( + record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), + record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON))); character.setTenantId(record.get(CHARACTERS.TENANT_ID)); character.setAccountId(record.get(CHARACTERS.ACCOUNT_ID)); character.setPlayableStateKey(record.get(CHARACTERS.PLAYABLE_STATE_KEY)); @@ -196,6 +237,17 @@ private Character toEntity(Record record) { return character; } + private Optional findStoredById(Long id) { + return Optional.ofNullable( + dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity)); + } + + private net.firedevops.firemud.entitymanagement.v1.PlayableStateScope scopeFrom(String value) { + return value == null + ? null + : net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf(value); + } + private InventoryEntry toInventoryEntry(Record record, Character character) { InventoryEntry entry = new InventoryEntry(); InventoryKey key = new InventoryKey(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java new file mode 100644 index 0000000000..fc49b7be18 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Holds ambiguous runtime evidence and quarantined-actor closure before instance cleanup. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class QuarantinedActorRetentionRepository { + private static final String HAS_UNRESOLVED_RUNTIME_EVIDENCE_SQL = + """ + SELECT + EXISTS ( + SELECT 1 + FROM item_instances item_instance + WHERE item_instance.tenant_id = ? + AND item_instance.game_instance_id = ? + ) + OR EXISTS ( + SELECT 1 + FROM container_instances container + WHERE container.tenant_id = ? + AND container.game_instance_id = ? + ) + OR EXISTS ( + SELECT 1 + FROM item_stacks stack + WHERE stack.tenant_id = ? + AND stack.game_instance_id = ? + ) + OR EXISTS ( + SELECT 1 + FROM room_ground_inventory ground + WHERE ground.tenant_id = ? + AND ground.game_instance_id = ? + ) + OR EXISTS ( + SELECT 1 + FROM item_transfer_audits audit + JOIN characters actor + ON actor.tenant_id = audit.tenant_id + AND actor.actor_identity_status = 'QUARANTINED' + AND ( + actor.id = audit.actor_character_id + OR actor.id = audit.source_character_id + OR actor.id = audit.destination_character_id + ) + WHERE audit.tenant_id = ? + AND ( + audit.source_game_instance_id = ? + OR audit.destination_game_instance_id = ? + ) + ) + """; + + private final DSLContext dsl; + + public QuarantinedActorRetentionRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public boolean hasUnresolvedRuntimeEvidence(Long tenantId, String gameInstanceId) { + Object retained = + dsl.fetchValue( + HAS_UNRESOLVED_RUNTIME_EVIDENCE_SQL, + tenantId, + gameInstanceId, + tenantId, + gameInstanceId, + tenantId, + gameInstanceId, + tenantId, + gameInstanceId, + tenantId, + gameInstanceId, + gameInstanceId); + return Boolean.TRUE.equals(retained); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java index 26283287d5..8bcd28175a 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java @@ -1,31 +1,25 @@ package net.firedevops.firemud.entitymanagement.service; -import lombok.RequiredArgsConstructor; +import java.util.Objects; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.springframework.stereotype.Service; @Service -@RequiredArgsConstructor -public class ScopedCharacterResolver { - private final CharacterRepository characterRepository; - private final PlayableStateKeyResolver playableStateKeyResolver; +public final class ScopedCharacterResolver { + public ScopedCharacterResolver( + CharacterRepository characterRepository, PlayableStateKeyResolver playableStateKeyResolver) { + Objects.requireNonNull(characterRepository); + Objects.requireNonNull(playableStateKeyResolver); + } public Character requireScopedCharacter( Long tenantId, Long characterId, String gameInstanceId, PlayableStateScope playableStateScope) { - String playableStateKey = playableStateKeyResolver.resolve(gameInstanceId, playableStateScope); - return characterRepository - .findByIdAndTenantIdAndPlayableStateKey(characterId, tenantId, playableStateKey) - .or( - () -> - characterRepository - .findByIdAndTenantId(characterId, tenantId) - .filter(character -> playableStateKey.equals(character.getPlayableStateKey()))) - .orElseThrow( - () -> new IllegalArgumentException("Character does not belong to gameplay scope")); + throw new IllegalArgumentException( + "OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED: legacy playableStateKey and runtime scope do not prove actor ownership"); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java index a6ec5bb285..c3f2886084 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java @@ -1,10 +1,6 @@ package net.firedevops.firemud.entitymanagement.service.impl; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.MeterRegistry; -import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.entitymanagement.dto.CharacterDto; import net.firedevops.firemud.entitymanagement.entity.Character; @@ -14,8 +10,6 @@ import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -23,29 +17,15 @@ @Service @RequiredArgsConstructor -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected dependencies are not exposed") public class CharacterServiceImpl implements CharacterService { private final CharacterRepository characterRepository; private final CharacterMapper characterMapper; - private final CacheManager cacheManager; - private final MeterRegistry meterRegistry; private final PlayableStateKeyResolver playableStateKeyResolver; private final ScopedCharacterResolver scopedCharacterResolver; - private Counter cacheHitCounter; - private Counter cacheMissCounter; - private static final int EXP_PER_LEVEL = 1000; - @PostConstruct - void initMetrics() { - cacheHitCounter = meterRegistry.counter("character_cache_hits_total"); - cacheMissCounter = meterRegistry.counter("character_cache_misses_total"); - } - @Override @Transactional @Timed(value = "character.create") @@ -77,21 +57,9 @@ public CharacterDto create( @Transactional(readOnly = true) @Timed(value = "character.get") public CharacterDto getWithInventory(Long characterId) { - Cache cache = cacheManager.getCache("characterGraph"); - if (cache != null) { - CharacterDto cached = cache.get(characterId, CharacterDto.class); - if (cached != null) { - cacheHitCounter.increment(); - return cached; - } - } - cacheMissCounter.increment(); + // Rely exclusively on the repository's fresh persisted OWNER_RESOLVED predicate. Character character = characterRepository.findWithInventoryById(characterId).orElseThrow(); - CharacterDto dto = toDto(character); - if (cache != null) { - cache.put(characterId, dto); - } - return dto; + return toDto(character); } @Override @@ -140,13 +108,7 @@ public Page listForGameplayScope( String gameInstanceId, PlayableStateScope playableStateScope, Pageable pageable) { - return characterRepository - .findByTenantIdAndAccountIdAndPlayableStateKey( - tenantId, - accountId, - playableStateKeyResolver.resolve(gameInstanceId, playableStateScope), - pageable) - .map(this::toDto); + return Page.empty(pageable == null ? Pageable.unpaged() : pageable); } @Override @@ -157,12 +119,7 @@ public java.util.Optional findByGameplayScopeAndName( if (name == null || name.isBlank()) { return java.util.Optional.empty(); } - return characterRepository - .findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( - tenantId, - playableStateKeyResolver.resolve(gameInstanceId, playableStateScope), - name.trim()) - .map(this::toDto); + return java.util.Optional.empty(); } private CharacterDto toDto(Character character) { @@ -172,7 +129,12 @@ private CharacterDto toDto(Character character) { dto.tenantId(), dto.accountId(), dto.name(), - playableStateKeyResolver.resolveScope(character.getPlayableStateKey()), + character.getActorIdentity() == null + || character.getActorIdentity().status() + != net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus + .OWNER_RESOLVED + ? PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED + : character.getActorIdentity().playableStateScope(), dto.level(), dto.experience(), dto.strength(), diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java index eb907e418d..7f1e246fe5 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java @@ -65,7 +65,7 @@ public EntityUpgradeValidationServiceImpl( public EntityUpgradeValidationResultDto validateEntityUpgradeMappings( long tenantId, long sourceGameInstanceId, long targetVersionId, String remapSetId) { String gameInstanceId = Long.toString(sourceGameInstanceId); - characterRepository.countByTenantId(tenantId); + long quarantinedActors = characterRepository.countQuarantinedByTenantId(tenantId); long inventoryRows = inventoryEntryRepository.countByCharacterTenantId(tenantId); long equipmentRows = characterEquipmentRepository.countByCharacterTenantId(tenantId); characterFriendRepository.countByTenantId(tenantId); @@ -75,6 +75,17 @@ public EntityUpgradeValidationResultDto validateEntityUpgradeMappings( roomGroundInventoryRepository.countByIdTenantIdAndIdGameInstanceId(tenantId, gameInstanceId); String normalizedRemapSetId = normalizeBlank(remapSetId); boolean hasTemplateBoundRows = inventoryRows > 0 || equipmentRows > 0; + if (quarantinedActors > 0) { + return new EntityUpgradeValidationResultDto( + STATE_CLASSES, + CHECKED_FAMILIES, + hasTemplateBoundRows, + "INCOMPATIBLE", + false, + List.of( + "ENTITY_ACTOR_IDENTITY_QUARANTINED: legacy actor identity lacks exact Account UUID and owner-resolved namespace/scope provenance"), + null); + } if (hasTemplateBoundRows && normalizedRemapSetId == null) { return new EntityUpgradeValidationResultDto( STATE_CLASSES, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java index 35532752c1..6c82d47d19 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.entitymanagement.repository.ContainerInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; +import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; import net.firedevops.firemud.entitymanagement.repository.RoomGroundInventoryRepository; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import org.springframework.stereotype.Service; @@ -19,16 +20,19 @@ public class RuntimeInstanceCleanupServiceImpl implements RuntimeInstanceCleanup private final ItemStackRepository itemStackRepository; private final ItemInstanceRepository itemInstanceRepository; private final ContainerInstanceRepository containerInstanceRepository; + private final QuarantinedActorRetentionRepository quarantinedActorRetentionRepository; public RuntimeInstanceCleanupServiceImpl( RoomGroundInventoryRepository roomGroundInventoryRepository, ItemStackRepository itemStackRepository, ItemInstanceRepository itemInstanceRepository, - ContainerInstanceRepository containerInstanceRepository) { + ContainerInstanceRepository containerInstanceRepository, + QuarantinedActorRetentionRepository quarantinedActorRetentionRepository) { this.roomGroundInventoryRepository = roomGroundInventoryRepository; this.itemStackRepository = itemStackRepository; this.itemInstanceRepository = itemInstanceRepository; this.containerInstanceRepository = containerInstanceRepository; + this.quarantinedActorRetentionRepository = quarantinedActorRetentionRepository; } @Override @@ -44,6 +48,11 @@ public RuntimeInstanceCleanupResultDto cleanupRuntimeInstance( if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } + if (quarantinedActorRetentionRepository.hasUnresolvedRuntimeEvidence( + tenantId, gameInstanceId)) { + throw new IllegalStateException( + "ENTITY_RETAINED_ACTOR_EVIDENCE_BLOCKS_CLEANUP: runtime holder ownership or quarantined actor audit evidence is unresolved"); + } long deletedRoomGroundEntries = roomGroundInventoryRepository.deleteByIdTenantIdAndIdGameInstanceId( tenantId, gameInstanceId); diff --git a/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql b/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql new file mode 100644 index 0000000000..fa0d31a2cf --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql @@ -0,0 +1,157 @@ +CREATE TABLE entity_playable_state_namespace_scopes ( + tenant_uuid UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_entity_playable_state_namespace_scopes + PRIMARY KEY (tenant_uuid, playable_state_namespace_id), + CONSTRAINT ck_entity_playable_state_namespace_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + )), + CONSTRAINT ck_entity_playable_state_namespace_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_playable_state_namespace_id_non_nil + CHECK (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ux_entity_playable_state_namespace_scope + UNIQUE (tenant_uuid, playable_state_namespace_id, playable_state_scope) +); + +ALTER TABLE characters + ADD COLUMN character_uuid UUID, + ADD COLUMN account_uuid UUID, + ADD COLUMN tenant_uuid UUID, + ADD COLUMN playable_state_namespace_id UUID, + ADD COLUMN playable_state_scope VARCHAR(40), + ADD COLUMN actor_identity_status VARCHAR(24) NOT NULL DEFAULT 'QUARANTINED', + ADD COLUMN actor_identity_quarantine_reason VARCHAR(80) + DEFAULT 'OWNER_PROVENANCE_MISSING'; + +UPDATE characters +SET character_uuid = gen_random_uuid(), + actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING'; + +ALTER TABLE characters + ALTER COLUMN character_uuid SET DEFAULT gen_random_uuid(); + +ALTER TABLE characters + ALTER COLUMN character_uuid SET NOT NULL; + +ALTER TABLE characters + ADD CONSTRAINT ux_characters_character_uuid UNIQUE (character_uuid); + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_character_uuid_non_nil + CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID); + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_status + CHECK (actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED')); + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_quarantine_reason + CHECK ( + (actor_identity_status = 'QUARANTINED' + AND actor_identity_quarantine_reason IS NOT NULL + AND length(trim(actor_identity_quarantine_reason)) > 0) + OR (actor_identity_status = 'OWNER_RESOLVED' + AND actor_identity_quarantine_reason IS NULL) + ); + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_uuid_non_nil + CHECK ( + (account_uuid IS NULL OR account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (tenant_uuid IS NULL OR tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (playable_state_namespace_id IS NULL OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ); + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_scope + CHECK ( + playable_state_scope IS NULL + OR playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + ) + ); + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_owner_resolved_provenance + CHECK ( + actor_identity_status <> 'OWNER_RESOLVED' + OR ( + account_uuid IS NOT NULL + AND tenant_uuid IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + ) + ); + +ALTER TABLE characters + ADD CONSTRAINT fk_characters_owner_resolved_namespace_scope + FOREIGN KEY (tenant_uuid, playable_state_namespace_id, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes ( + tenant_uuid, + playable_state_namespace_id, + playable_state_scope + ); + +CREATE INDEX idx_characters_owner_resolved_roster + ON characters ( + tenant_uuid, + account_uuid, + playable_state_namespace_id, + playable_state_scope, + character_uuid + ) + WHERE actor_identity_status = 'OWNER_RESOLVED'; + +/* [jooq ignore start] */ +CREATE VIEW entity_quarantined_actor_item_instances AS +WITH RECURSIVE retained_item_instances(tenant_id, item_instance_id) AS ( + SELECT item_instance.tenant_id, item_instance.id + FROM item_instances item_instance + JOIN characters actor + ON actor.id = item_instance.character_id + AND actor.actor_identity_status = 'QUARANTINED' + + UNION + + SELECT container.tenant_id, container.item_instance_id + FROM container_instances container + JOIN characters actor + ON actor.id = container.character_id + AND actor.actor_identity_status = 'QUARANTINED' + WHERE container.item_instance_id IS NOT NULL + + UNION + + SELECT child_item.tenant_id, child_item.id + FROM retained_item_instances retained_parent + JOIN container_instances parent_container + ON parent_container.tenant_id = retained_parent.tenant_id + AND parent_container.item_instance_id = retained_parent.item_instance_id + JOIN item_instances child_item + ON child_item.tenant_id = parent_container.tenant_id + AND child_item.container_instance_id = parent_container.id +) +SELECT DISTINCT tenant_id, item_instance_id +FROM retained_item_instances; + +CREATE VIEW entity_quarantined_actor_container_instances AS +SELECT DISTINCT container.tenant_id, container.id AS container_instance_id +FROM container_instances container +JOIN characters actor + ON actor.id = container.character_id + AND actor.actor_identity_status = 'QUARANTINED' + +UNION + +SELECT DISTINCT container.tenant_id, container.id AS container_instance_id +FROM container_instances container +JOIN entity_quarantined_actor_item_instances retained_item + ON retained_item.tenant_id = container.tenant_id + AND retained_item.item_instance_id = container.item_instance_id; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java index faff2df762..58b6e9a188 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java @@ -2,6 +2,9 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.HashMap; +import java.util.Map; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.Item; import net.firedevops.firemud.entitymanagement.entity.ItemStackCompatibilityMode; @@ -12,10 +15,12 @@ import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; import net.firedevops.firemud.entitymanagement.service.ContainerService; import net.firedevops.firemud.entitymanagement.service.InventoryService; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -30,6 +35,12 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +/** + * Conditional PostgreSQL proof for holder persistence after an assumed actor scope guard. The + * mocked resolver admits only explicitly registered saved-character fixtures with the exact test + * tenant, instance, and scope; those rows remain quarantined. This class proves nested holder and + * persistence behavior, not owner provenance, runtime admission, or PLAY activation. + */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @SpringBootTest( @@ -42,6 +53,7 @@ class ContainerInstanceLocationIntegrationTest { private static final String ROOM_INSTANCE_ID = "R-1"; private static final PlayableStateScope PLAYABLE_STATE_SCOPE = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + private final Map registeredCharacterFixtures = new HashMap<>(); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -67,9 +79,34 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private JdbcTemplate jdbcTemplate; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private ScopedCharacterResolver scopedCharacterResolver; @BeforeEach void cleanDatabase() { + registeredCharacterFixtures.clear(); + Mockito.doAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + Long characterId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope playableStateScope = invocation.getArgument(3); + Character character = registeredCharacterFixtures.get(characterId); + if (!TENANT_ID.equals(tenantId) + || !GAME_INSTANCE_ID.equals(gameInstanceId) + || PLAYABLE_STATE_SCOPE != playableStateScope + || character == null + || !TENANT_ID.equals(character.getTenantId())) { + throw new IllegalArgumentException( + "Test scoped resolver fixture does not match requested tenant, character, instance, or scope"); + } + return character; + }) + .when(scopedCharacterResolver) + .requireScopedCharacter( + Mockito.nullable(Long.class), + Mockito.nullable(Long.class), + Mockito.nullable(String.class), + Mockito.nullable(PlayableStateScope.class)); jdbcTemplate.execute( "TRUNCATE TABLE item_stacks, item_instances, container_instances, items, characters RESTART IDENTITY CASCADE"); } @@ -78,6 +115,8 @@ void cleanDatabase() { void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { Character alice = characterRepository.save(character("Alice")); Character bob = characterRepository.save(character("Bob")); + registerCharacterFixture(alice); + registerCharacterFixture(bob); Item backpack = itemRepository.save(containerItem("Backpack")); Item torch = itemRepository.save(ordinaryItem("Torch")); @@ -184,6 +223,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { @Test void identicalContainersKeepDistinctContentsByContainerInstance() { Character alice = characterRepository.save(character("Alice")); + registerCharacterFixture(alice); Item backpack = itemRepository.save(containerItem("Backpack")); Item torch = itemRepository.save(ordinaryItem("Torch")); Item ration = itemRepository.save(ordinaryItem("Ration")); @@ -289,6 +329,12 @@ private Character character(String name) { return character; } + private void registerCharacterFixture(Character character) { + assertThat(character.getActorIdentity()).isNotNull(); + assertThat(character.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); + registeredCharacterFixtures.put(character.getId(), character); + } + private Item containerItem(String name) { Item item = ordinaryItem(name); item.setContainer(true); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java new file mode 100644 index 0000000000..7e0800a2c9 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -0,0 +1,846 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; +import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; +import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.repository.ActorActiveConditionRepository; +import net.firedevops.firemud.entitymanagement.repository.ActorIdentityRepository; +import net.firedevops.firemud.entitymanagement.repository.ActorResourceStateRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; +import net.firedevops.firemud.entitymanagement.service.CharacterService; +import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = WebEnvironment.NONE, + classes = EntityManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class RetainedActorIdentityIntegrationTest { + private static final long TENANT_ID = 72L; + private static final long ACCOUNT_ID = 88L; + private static final String INSTANCE_ID = "GI-RETAINED"; + private static final UUID TENANT_UUID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID ACCOUNT_UUID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("30000000-0000-4000-8000-000000000003"); + private String migrationSchema; + + @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, "entity_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private ActorIdentityRepository actorIdentityRepository; + @Autowired private CharacterRepository characterRepository; + @Autowired private ActorActiveConditionRepository actorActiveConditionRepository; + @Autowired private ActorResourceStateRepository actorResourceStateRepository; + @Autowired private QuarantinedActorRetentionRepository quarantinedActorRetentionRepository; + @Autowired private RuntimeInstanceCleanupService runtimeInstanceCleanupService; + @Autowired private ScopedCharacterResolver scopedCharacterResolver; + @Autowired private CharacterService characterService; + @Autowired private JdbcTemplate jdbcTemplate; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @BeforeEach + void clearServiceSchema() { + jdbcTemplate.execute( + "TRUNCATE TABLE entity_mutation_effects, item_transfer_audits, actor_active_conditions, " + + "actor_resource_states, character_friend, character_equipment, inventory, item_stacks, " + + "item_instances, container_instances, room_ground_inventory, items, characters, " + + "entity_playable_state_namespace_scopes RESTART IDENTITY CASCADE"); + } + + @Test + void canonicalRosterIsExactOrderedAndExcludesLegacyQuarantine() { + insertNamespace(TENANT_UUID, NAMESPACE_UUID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + UUID first = UUID.fromString("40000000-0000-4000-8000-000000000001"); + UUID second = UUID.fromString("40000000-0000-4000-8000-000000000002"); + UUID third = UUID.fromString("40000000-0000-4000-8000-000000000003"); + long legacyId = + insertActor( + "legacy-shared", + UUID.fromString("40000000-0000-4000-8000-000000000000"), + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + ACCOUNT_ID, + TENANT_ID); + + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat(characterRepository.findByIdAndTenantId(legacyId, TENANT_ID)).isEmpty(); + + insertActor( + "third", + third, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + ACCOUNT_ID, + TENANT_ID); + insertActor( + "first", + first, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + ACCOUNT_ID, + TENANT_ID); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(first, third); + insertActor( + "second", + second, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + ACCOUNT_ID, + TENANT_ID); + + var roster = + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(roster) + .extracting(identity -> identity.characterUuid()) + .containsExactly(first, second, third); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + first.toString())) + .get() + .extracting(identity -> identity.characterUuid()) + .isEqualTo(first); + + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + "50000000-0000-4000-8000-000000000005", + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + "60000000-0000-4000-8000-000000000006", + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + "70000000-0000-4000-8000-000000000007", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "40000000-0000-4000-8000-000000000000")) + .isEmpty(); + + assertThatThrownBy( + () -> + actorIdentityRepository.findOwnerResolvedRoster( + null, + ACCOUNT_UUID.toString(), + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + ACCOUNT_UUID.toString(), + "not-a-uuid", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + actorIdentityRepository.findOwnerResolvedRoster( + TENANT_UUID.toString(), + "00000000-0000-0000-0000-000000000000", + NAMESPACE_UUID.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + insertNamespace( + TENANT_UUID, NAMESPACE_UUID, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_playable_state_namespace_scopes SET playable_state_scope = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED.name(), + TENANT_UUID, + NAMESPACE_UUID)) + .isInstanceOf(RuntimeException.class); + } + + @Test + void quarantinedActorLookupMutationExpiryAndCleanupRemainHeld() { + Character actor = new Character(); + actor.setTenantId(TENANT_ID); + actor.setAccountId(ACCOUNT_ID); + actor.setPlayableStateKey("instance:" + INSTANCE_ID); + actor.setName("Retained actor"); + actor.setExperience(17); + actor = characterRepository.save(actor); + long actorId = actor.getId(); + assertThat(actor.getActorIdentity().status().name()).isEqualTo("QUARANTINED"); + assertThat(actor.getActorIdentity().characterUuid()).isNotNull(); + assertThat(characterRepository.findById(actorId)).isEmpty(); + + ActorResourceState resourceWrite = new ActorResourceState(); + resourceWrite.setTenantId(TENANT_ID); + resourceWrite.setCharacterId(actorId); + resourceWrite.setPlayableStateKey("instance:" + INSTANCE_ID); + resourceWrite.setStatKey("health"); + resourceWrite.setCurrentValue(31L); + assertThatThrownBy(() -> actorResourceStateRepository.save(resourceWrite)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + + ActorActiveCondition conditionWrite = new ActorActiveCondition(); + conditionWrite.setTenantId(TENANT_ID); + conditionWrite.setCharacterId(actorId); + conditionWrite.setPlayableStateKey("instance:" + INSTANCE_ID); + conditionWrite.setConditionKey("stunned"); + conditionWrite.setSourceType("TEST"); + assertThatThrownBy(() -> actorActiveConditionRepository.save(conditionWrite)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + + jdbcTemplate.update( + "INSERT INTO items (id, name, tenant_id, is_container) VALUES " + + "(3001, 'Backpack', ?, true), (3002, 'Pouch', ?, true), (3003, 'Gem', ?, false)", + TENANT_ID, + TENANT_ID, + TENANT_ID); + jdbcTemplate.update( + "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (?, 3003, 5, 2)", + actorId); + jdbcTemplate.update( + "INSERT INTO character_equipment (character_id, slot, item_id, version) " + + "VALUES (?, 'hand', 3003, 3)", + actorId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) " + + "VALUES (?, ?, ?, 'pending')", + actorId, + actorId, + TENANT_ID); + jdbcTemplate.update( + "INSERT INTO actor_resource_states " + + "(tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) " + + "VALUES (?, ?, 'health', 31, 90, 40, 'LEGACY_SOURCE', 'source-17', ?, 4)", + TENANT_ID, + actorId, + "instance:" + INSTANCE_ID); + jdbcTemplate.update( + "INSERT INTO actor_active_conditions " + + "(tenant_id, character_id, condition_key, stack_count, source_type, source_id, started_at, expires_at, effect_payload_json, playable_state_key, version) " + + "VALUES (?, ?, 'stunned', 3, 'LEGACY_SOURCE', 'condition-19', '2020-01-01T00:00:00Z', '2020-01-02T00:00:00Z', '{\"modifier\":2}', ?, 5)", + TENANT_ID, + actorId, + "instance:" + INSTANCE_ID); + + jdbcTemplate.update( + "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) " + + "VALUES (3101, ?, ?, ?, 3001, 6)", + TENANT_ID, + actorId, + INSTANCE_ID); + insertItemInstance(3201, actorId, INSTANCE_ID, null, 3001, "retained-backpack"); + jdbcTemplate.update("UPDATE container_instances SET item_instance_id = 3201 WHERE id = 3101"); + insertItemInstance(3202, null, INSTANCE_ID, 3101L, 3002, "retained-pouch"); + jdbcTemplate.update( + "INSERT INTO container_instances (id, tenant_id, game_instance_id, item_id, version, item_instance_id) " + + "VALUES (3102, ?, ?, 3002, 7, 3202)", + TENANT_ID, + INSTANCE_ID); + insertItemInstance(3203, null, INSTANCE_ID, 3102L, 3003, "retained-gem"); + jdbcTemplate.update( + "INSERT INTO item_stacks (id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) " + + "VALUES (3301, ?, ?, ?, 3003, 'actor-stack', 8, 2, 'actor-family')", + TENANT_ID, + actorId, + INSTANCE_ID); + jdbcTemplate.update( + "INSERT INTO item_stacks (id, tenant_id, game_instance_id, container_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) " + + "VALUES (3302, ?, ?, 3102, 3003, 'nested-stack', 9, 3, 'nested-family')", + TENANT_ID, + INSTANCE_ID); + jdbcTemplate.update( + "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " + + "VALUES (?, ?, 'room-retained', 3003, 11, 8)", + TENANT_ID, + INSTANCE_ID); + jdbcTemplate.update( + "INSERT INTO item_transfer_audits " + + "(id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) " + + "VALUES (3401, ?, 3001, 3201, 1, 'DROP', ?, 'effect-retained', 'corr-retained', 'CHARACTER', ?, ?, 'ROOM', ?, 'room-retained')", + TENANT_ID, + actorId, + actorId, + INSTANCE_ID, + INSTANCE_ID); + jdbcTemplate.update( + "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) " + + "VALUES (3501, ?, 'effect-retained', 'DROP', 'DropResponse', decode('aabb', 'hex'), 'APPLIED')", + TENANT_ID); + + assertThatThrownBy( + () -> + scopedCharacterResolver.requireScopedCharacter( + TENANT_ID, + actorId, + INSTANCE_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); + assertThatThrownBy( + () -> + characterService.gainExperience( + TENANT_ID, + actorId, + INSTANCE_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + 100)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + runtimeInstanceCleanupService.cleanupRuntimeInstance( + TENANT_ID, INSTANCE_ID, "termination-retained")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ENTITY_RETAINED_ACTOR_EVIDENCE_BLOCKS_CLEANUP"); + + assertThat( + quarantinedActorRetentionRepository.hasUnresolvedRuntimeEvidence( + TENANT_ID, INSTANCE_ID)) + .isTrue(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_quarantined_actor_item_instances WHERE tenant_id = ?", + Integer.class, + TENANT_ID)) + .isEqualTo(3); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_quarantined_actor_container_instances WHERE tenant_id = ?", + Integer.class, + TENANT_ID)) + .isEqualTo(2); + assertThat(actorActiveConditionRepository.deleteExpired(Instant.parse("2030-01-01T00:00:00Z"))) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT experience FROM characters WHERE id = ?", Integer.class, actorId)) + .isEqualTo(17); + assertThat( + jdbcTemplate.queryForObject( + "SELECT quantity FROM inventory WHERE character_id = ? AND item_id = 3003", + Integer.class, + actorId)) + .isEqualTo(5); + assertThat( + jdbcTemplate.queryForObject( + "SELECT version FROM character_equipment WHERE character_id = ? AND slot = 'hand'", + Integer.class, + actorId)) + .isEqualTo(3); + assertThat( + jdbcTemplate.queryForObject( + "SELECT status FROM character_friend WHERE character_id = ? AND friend_id = ?", + String.class, + actorId, + actorId)) + .isEqualTo("pending"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE character_id = ? AND stat_key = 'health'", + Long.class, + actorId)) + .isEqualTo(31L); + assertThat( + jdbcTemplate.queryForObject( + "SELECT effect_payload_json FROM actor_active_conditions WHERE character_id = ?", + String.class, + actorId)) + .isEqualTo("{\"modifier\":2}"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_instances WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + INSTANCE_ID)) + .isEqualTo(3); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + INSTANCE_ID)) + .isEqualTo(2); + assertThat( + jdbcTemplate.queryForObject( + "SELECT sum(quantity) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + INSTANCE_ID)) + .isEqualTo(17); + assertThat( + jdbcTemplate.queryForObject( + "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + INSTANCE_ID)) + .isEqualTo(11); + assertThat( + jdbcTemplate.queryForObject( + "SELECT correlation_key FROM item_transfer_audits WHERE id = 3401", String.class)) + .isEqualTo("corr-retained"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = 3501", + String.class)) + .isEqualTo("aabb"); + } + + @Test + void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { + insertActor( + "legacy shared actor", + UUID.fromString("41000000-0000-4000-8000-000000000001"), + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + ACCOUNT_ID, + TENANT_ID); + jdbcTemplate.update( + "INSERT INTO items (id, name, tenant_id, is_container) VALUES (3901, 'Unresolved ground item', ?, false)", + TENANT_ID); + jdbcTemplate.update( + "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " + + "VALUES (?, ?, 'room-unresolved', 3901, 2, 1)", + TENANT_ID, + INSTANCE_ID); + + assertThat( + quarantinedActorRetentionRepository.hasUnresolvedRuntimeEvidence( + TENANT_ID, INSTANCE_ID)) + .isTrue(); + assertThatThrownBy( + () -> + runtimeInstanceCleanupService.cleanupRuntimeInstance( + TENANT_ID, INSTANCE_ID, "termination-unresolved-ground")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ENTITY_RETAINED_ACTOR_EVIDENCE_BLOCKS_CLEANUP"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + INSTANCE_ID)) + .isEqualTo(2); + } + + @Test + void flywayV1ToV2RetainsLegacyRowsAndEveryDependentStateFamily() throws SQLException { + migrateLegacySchemaToV1(); + try (Connection connection = connectToMigrationSchema()) { + var statement = connection.createStatement(); + statement.executeUpdate( + "INSERT INTO characters (id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key) " + + "VALUES (101, 81, 'Legacy Shared', 71, 'shared-live', 9, 17, 21, 22, 23, 24, 31, 32, 12, 'LEGACY_BODY'), " + + "(102, 81, 'Legacy Instance', 71, 'instance:44', 3, 7, 11, 12, 13, 14, 15, 16, 5, 'LEGACY_BODY')"); + statement.executeUpdate( + "INSERT INTO items (id, name, tenant_id, is_container) VALUES (201, 'Bag', 71, true), (202, 'Gem', 71, false)"); + statement.executeUpdate( + "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (101, 202, 6, 3)"); + statement.executeUpdate( + "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) VALUES (101, 102, 71, 'pending')"); + statement.executeUpdate( + "INSERT INTO character_equipment (character_id, slot, item_id, version) VALUES (101, 'hand', 202, 4)"); + statement.executeUpdate( + "INSERT INTO actor_resource_states (id, tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) VALUES (301, 71, 101, 'health', 31, 90, 40, 'LEGACY_SOURCE', 'resource-source', 'shared-live', 8)"); + statement.executeUpdate( + "INSERT INTO actor_active_conditions (id, tenant_id, character_id, condition_key, stack_count, source_type, source_id, started_at, expires_at, effect_payload_json, playable_state_key, version) VALUES (302, 71, 101, 'stunned', 3, 'LEGACY_SOURCE', 'condition-source', '2020-01-01T00:00:00Z', '2020-01-02T00:00:00Z', '{\"modifier\":2}', 'shared-live', 9)"); + statement.executeUpdate( + "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) VALUES (401, 71, 101, '44', 201, 10)"); + statement.executeUpdate( + "INSERT INTO item_instances (id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) VALUES (501, 71, 101, '44', NULL, 201, 'legacy', 1, 'legacy-bag', 11)"); + statement.executeUpdate( + "UPDATE container_instances SET item_instance_id = 501 WHERE id = 401"); + statement.executeUpdate( + "INSERT INTO item_instances (id, tenant_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) VALUES (502, 71, '44', 401, 202, 'legacy', 2, 'legacy-gem', 12)"); + statement.executeUpdate( + "INSERT INTO item_stacks (id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) VALUES (601, 71, 101, '44', 202, 'legacy-fingerprint', 13, 14, 'legacy-family')"); + statement.executeUpdate( + "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) VALUES (71, '44', 'room-9', 202, 15, 16)"); + statement.executeUpdate( + "INSERT INTO item_transfer_audits (id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) VALUES (701, 71, 202, 502, 2, 'DROP', 101, 'legacy-effect', 'legacy-correlation', 'CHARACTER', 101, '44', 'ROOM', '44', 'room-9')"); + statement.executeUpdate( + "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) VALUES (801, 71, 'legacy-effect', 'DROP', 'DropResponse', decode('cafe', 'hex'), 'APPLIED')"); + statement.close(); + } + + migrateLegacySchemaToLatest(); + + try (Connection connection = connectToMigrationSchema(); + var statement = connection.createStatement()) { + try (var rows = + statement.executeQuery( + "SELECT id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason FROM characters ORDER BY id")) { + assertThat(rows.next()).isTrue(); + UUID firstActorUuid = rows.getObject("character_uuid", UUID.class); + assertThat(firstActorUuid).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(rows.getLong("id")).isEqualTo(101L); + assertThat(rows.getLong("account_id")).isEqualTo(81L); + assertThat(rows.getString("name")).isEqualTo("Legacy Shared"); + assertThat(rows.getLong("tenant_id")).isEqualTo(71L); + assertThat(rows.getString("playable_state_key")).isEqualTo("shared-live"); + assertThat(rows.getInt("level")).isEqualTo(9); + assertThat(rows.getInt("experience")).isEqualTo(17); + assertThat(rows.getInt("strength")).isEqualTo(21); + assertThat(rows.getInt("agility")).isEqualTo(22); + assertThat(rows.getInt("intelligence")).isEqualTo(23); + assertThat(rows.getInt("stamina")).isEqualTo(24); + assertThat(rows.getInt("health")).isEqualTo(31); + assertThat(rows.getInt("mana")).isEqualTo(32); + assertThat(rows.getInt("version")).isEqualTo(12); + assertThat(rows.getString("body_layout_key")).isEqualTo("LEGACY_BODY"); + assertThat(rows.getObject("account_uuid")).isNull(); + assertThat(rows.getObject("tenant_uuid")).isNull(); + assertThat(rows.getObject("playable_state_namespace_id")).isNull(); + assertThat(rows.getString("playable_state_scope")).isNull(); + assertThat(rows.getString("actor_identity_status")).isEqualTo("QUARANTINED"); + assertThat(rows.getString("actor_identity_quarantine_reason")) + .isEqualTo("OWNER_PROVENANCE_MISSING"); + assertThat(rows.next()).isTrue(); + UUID secondActorUuid = rows.getObject("character_uuid", UUID.class); + assertThat(secondActorUuid).isNotNull().isNotEqualTo(firstActorUuid); + assertThat(rows.getLong("id")).isEqualTo(102L); + assertThat(rows.getLong("account_id")).isEqualTo(81L); + assertThat(rows.getLong("tenant_id")).isEqualTo(71L); + assertThat(rows.getString("playable_state_key")).isEqualTo("instance:44"); + assertThat(rows.getString("actor_identity_status")).isEqualTo("QUARANTINED"); + assertThat(rows.getObject("account_uuid")).isNull(); + assertThat(rows.getObject("playable_state_namespace_id")).isNull(); + assertThat(rows.next()).isFalse(); + } + assertThat( + readLong( + statement, + "SELECT quantity FROM inventory WHERE character_id = 101 AND item_id = 202")) + .isEqualTo(6L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', character_id, item_id, quantity, version) FROM inventory WHERE character_id = 101 AND item_id = 202")) + .isEqualTo("101|202|6|3"); + assertThat( + readString(statement, "SELECT status FROM character_friend WHERE character_id = 101")) + .isEqualTo("pending"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', character_id, friend_id, tenant_id, status) FROM character_friend WHERE character_id = 101")) + .isEqualTo("101|102|71|pending"); + assertThat( + readLong( + statement, "SELECT version FROM character_equipment WHERE character_id = 101")) + .isEqualTo(4L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', character_id, slot, item_id, version) FROM character_equipment WHERE character_id = 101")) + .isEqualTo("101|hand|202|4"); + assertThat( + readLong(statement, "SELECT current_value FROM actor_resource_states WHERE id = 301")) + .isEqualTo(31L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) FROM actor_resource_states WHERE id = 301")) + .isEqualTo("301|71|101|health|31|90|40|LEGACY_SOURCE|resource-source|shared-live|8"); + assertThat( + readString( + statement, + "SELECT effect_payload_json FROM actor_active_conditions WHERE id = 302")) + .isEqualTo("{\"modifier\":2}"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, condition_key, stack_count, source_type, source_id, playable_state_key, version) FROM actor_active_conditions WHERE id = 302")) + .isEqualTo("302|71|101|stunned|3|LEGACY_SOURCE|condition-source|shared-live|9"); + assertThat( + readLong( + statement, + "SELECT extract(epoch FROM started_at)::bigint FROM actor_active_conditions WHERE id = 302")) + .isEqualTo(1577836800L); + assertThat( + readLong( + statement, + "SELECT extract(epoch FROM expires_at)::bigint FROM actor_active_conditions WHERE id = 302")) + .isEqualTo(1577923200L); + assertThat(readLong(statement, "SELECT count(*) FROM item_instances WHERE id IN (501, 502)")) + .isEqualTo(2L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) FROM item_instances WHERE id = 501")) + .isEqualTo("501|71|101|44|201|legacy|1|legacy-bag|11"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) FROM item_instances WHERE id = 502")) + .isEqualTo("502|71|44|401|202|legacy|2|legacy-gem|12"); + assertThat( + readLong( + statement, "SELECT container_instance_id FROM item_instances WHERE id = 502")) + .isEqualTo(401L); + assertThat( + readLong( + statement, "SELECT item_instance_id FROM container_instances WHERE id = 401")) + .isEqualTo(501L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, item_id, item_instance_id, version) FROM container_instances WHERE id = 401")) + .isEqualTo("401|71|101|44|201|501|10"); + assertThat(readLong(statement, "SELECT quantity FROM item_stacks WHERE id = 601")) + .isEqualTo(13L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) FROM item_stacks WHERE id = 601")) + .isEqualTo("601|71|101|44|202|legacy-fingerprint|13|14|legacy-family"); + assertThat( + readLong( + statement, + "SELECT quantity FROM room_ground_inventory WHERE room_instance_id = 'room-9'")) + .isEqualTo(15L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) FROM room_ground_inventory WHERE room_instance_id = 'room-9'")) + .isEqualTo("71|44|room-9|202|15|16"); + assertThat( + readString( + statement, "SELECT correlation_key FROM item_transfer_audits WHERE id = 701")) + .isEqualTo("legacy-correlation"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) FROM item_transfer_audits WHERE id = 701")) + .isEqualTo( + "701|71|202|502|2|DROP|101|legacy-effect|legacy-correlation|CHARACTER|101|44|ROOM|44|room-9"); + assertThat( + readString( + statement, + "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = 801")) + .isEqualTo("cafe"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, effect_id, operation_name, response_type, encode(response_payload, 'hex'), status) FROM entity_mutation_effects WHERE id = 801")) + .isEqualTo("801|71|legacy-effect|DROP|DropResponse|cafe|APPLIED"); + } + } + + private void insertNamespace(UUID tenantUuid, UUID namespaceUuid, PlayableStateScope scope) { + jdbcTemplate.update( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?)", + tenantUuid, + namespaceUuid, + scope.name()); + } + + private long insertActor( + String name, + UUID characterUuid, + UUID accountUuid, + UUID tenantUuid, + UUID namespaceUuid, + PlayableStateScope scope, + String legacyStateKey, + String status, + String quarantineReason, + long legacyAccountId, + long legacyTenantId) { + return jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + Long.class, + legacyAccountId, + name, + legacyTenantId, + legacyStateKey, + characterUuid, + accountUuid, + tenantUuid, + namespaceUuid, + scope == null ? null : scope.name(), + status, + quarantineReason); + } + + private void insertItemInstance( + long id, + Long characterId, + String gameInstanceId, + Long containerId, + long itemId, + String visibleRef) { + jdbcTemplate.update( + "INSERT INTO item_instances (id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)", + id, + TENANT_ID, + characterId, + gameInstanceId, + containerId, + itemId, + "retained", + id, + visibleRef); + } + + private void migrateLegacySchemaToV1() throws SQLException { + migrationSchema = "retained_actor_v1_to_v2_" + UUID.randomUUID().toString().replace("-", ""); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + migrationSchema); + } + migrationFlyway().target(MigrationVersion.fromVersion("1")).load().migrate(); + } + + private void migrateLegacySchemaToLatest() { + migrationFlyway().load().migrate(); + } + + private FluentConfiguration migrationFlyway() { + return Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(migrationSchema) + .defaultSchema(migrationSchema) + .locations("classpath:db/migration"); + } + + private Connection connectToMigrationSchema() throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + try (var statement = connection.createStatement()) { + statement.execute("SET search_path TO " + migrationSchema); + } + return connection; + } + + private long readLong(java.sql.Statement statement, String sql) throws SQLException { + try (var rows = statement.executeQuery(sql)) { + assertThat(rows.next()).isTrue(); + return rows.getLong(1); + } + } + + private String readString(java.sql.Statement statement, String sql) throws SQLException { + try (var rows = statement.executeQuery(sql)) { + assertThat(rows.next()).isTrue(); + return rows.getString(1); + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java new file mode 100644 index 0000000000..e4ec45fe07 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.entitymanagement.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class ActorIdentityValueTest { + private static final UUID ACTOR_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void parsesOnlyCompleteNonNilUuidValues() { + assertEquals(ACTOR_UUID, ActorIdentity.parseRequiredUuid(ACTOR_UUID.toString(), "actor")); + assertThrows( + IllegalArgumentException.class, () -> ActorIdentity.parseRequiredUuid(null, "actor")); + assertThrows( + IllegalArgumentException.class, + () -> ActorIdentity.parseRequiredUuid("not-a-uuid", "actor")); + assertThrows( + IllegalArgumentException.class, + () -> ActorIdentity.parseRequiredUuid("00000000-0000-0000-0000-000000000000", "actor")); + } + + @Test + void ownerResolvedIdentityRequiresExactAccountTenantNamespaceAndScope() { + var identity = + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null); + assertEquals(ActorIdentityStatus.OWNER_RESOLVED, identity.status()); + + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + null, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + "LEGACY_IDENTITY")); + } + + @Test + void quarantineCanRetainIncompleteSourceProvenanceWithoutCreatingAnAlias() { + var quarantined = + new ActorIdentity( + ACTOR_UUID, + null, + null, + null, + null, + ActorIdentityStatus.QUARANTINED, + "OWNER_PROVENANCE_MISSING"); + assertEquals(ActorIdentityStatus.QUARANTINED, quarantined.status()); + + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + new UUID(0L, 0L), + null, + null, + null, + null, + ActorIdentityStatus.QUARANTINED, + "OWNER_PROVENANCE_MISSING")); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, ACCOUNT_UUID, null, null, null, ActorIdentityStatus.QUARANTINED, " ")); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java new file mode 100644 index 0000000000..102694fedd --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.entitymanagement.service; + +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.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class ScopedCharacterResolverTest { + @Test + void rejectsLegacyScopeEvenWhenRepositoryCanReturnOwnerResolvedCandidate() { + CharacterRepository repository = mock(CharacterRepository.class); + Character candidate = new Character(); + candidate.setId(17L); + candidate.setTenantId(23L); + candidate.setActorIdentity( + new ActorIdentity( + UUID.fromString("40000000-0000-4000-8000-000000000001"), + UUID.fromString("20000000-0000-4000-8000-000000000002"), + UUID.fromString("10000000-0000-4000-8000-000000000001"), + UUID.fromString("30000000-0000-4000-8000-000000000003"), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + when(repository.findByIdAndTenantIdAndPlayableStateKey(17L, 23L, "shared-live")) + .thenReturn(Optional.of(candidate)); + + assertThat(repository.findByIdAndTenantIdAndPlayableStateKey(17L, 23L, "shared-live")) + .hasValueSatisfying(found -> assertThat(found).isSameAs(candidate)); + + ScopedCharacterResolver resolver = + new ScopedCharacterResolver(repository, new PlayableStateKeyResolver()); + assertThatThrownBy( + () -> + resolver.requireScopedCharacter( + 23L, 17L, "GI-1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java index 3c16b64078..2bab84dc06 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java @@ -1,12 +1,8 @@ package net.firedevops.firemud.entitymanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verifyNoInteractions; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.List; -import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; @@ -15,72 +11,44 @@ import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import org.mockito.Mockito; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; -import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; class CharacterServiceImplListTest { @Test - void listForTenantAndAccountReturnsDtos() { + void legacyGameplayRosterRemainsClosedWithoutOwnerResolvedIdentity() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); - var cacheManager = new ConcurrentMapCacheManager("characterGraph"); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); CharacterServiceImpl service = new CharacterServiceImpl( repo, mapper, - cacheManager, - meterRegistry, new PlayableStateKeyResolver(), new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); - service.initMetrics(); - - Character c = new Character(); - c.setId(1L); - c.setTenantId(1L); - c.setAccountId(1L); - c.setPlayableStateKey("shared-live"); - c.setName("Hero"); - - when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( - 1L, 1L, "shared-live", Pageable.unpaged())) - .thenReturn(new PageImpl<>(List.of(c))); var result = service.listForGameplayScope( 1L, 1L, "44", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, Pageable.unpaged()); - assertEquals(1, result.getTotalElements()); - assertEquals("Hero", result.getContent().get(0).name()); - verify(repo) - .findByTenantIdAndAccountIdAndPlayableStateKey(1L, 1L, "shared-live", Pageable.unpaged()); + assertEquals(0, result.getTotalElements()); + assertEquals(0, result.getContent().size()); + verifyNoInteractions(repo); } @Test void listForTenantAndAccountDoesNotCrossTenantBoundary() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); - var cacheManager = new ConcurrentMapCacheManager("characterGraph"); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); CharacterServiceImpl service = new CharacterServiceImpl( repo, mapper, - cacheManager, - meterRegistry, new PlayableStateKeyResolver(), new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); - service.initMetrics(); - - when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( - 2L, 1L, "instance:91", Pageable.unpaged())) - .thenReturn(new PageImpl<>(List.of())); var result = service.listForGameplayScope( 2L, 1L, "91", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, Pageable.unpaged()); assertEquals(0, result.getTotalElements()); - verify(repo) - .findByTenantIdAndAccountIdAndPlayableStateKey(2L, 1L, "instance:91", Pageable.unpaged()); + assertEquals(0, result.getContent().size()); + verifyNoInteractions(repo); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java index f6b8c8bbff..ed18f394c3 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java @@ -4,9 +4,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.entitymanagement.dto.CharacterDto; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; @@ -16,7 +18,6 @@ import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import org.mockito.Mockito; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; class CharacterServiceImplTest { @@ -24,17 +25,6 @@ class CharacterServiceImplTest { void gainExperienceLevelsUp() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); - var cacheManager = new ConcurrentMapCacheManager("characterGraph"); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - CharacterServiceImpl service = - new CharacterServiceImpl( - repo, - mapper, - cacheManager, - meterRegistry, - new PlayableStateKeyResolver(), - new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); - service.initMetrics(); Character character = new Character(); character.setId(1L); @@ -50,9 +40,15 @@ void gainExperienceLevelsUp() { character.setStamina(1); character.setHealth(10); character.setMana(5); + character.setActorIdentity( + ownerResolvedIdentity(1L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); - when(repo.findByIdAndTenantIdAndPlayableStateKey(1L, 1L, "shared-live")) - .thenReturn(Optional.of(character)); + ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); + when(resolver.requireScopedCharacter( + 1L, 1L, "live", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(character); + CharacterServiceImpl service = + new CharacterServiceImpl(repo, mapper, new PlayableStateKeyResolver(), resolver); when(repo.save(any(Character.class))).thenAnswer(a -> a.getArgument(0)); CharacterDto dto = @@ -67,17 +63,12 @@ void gainExperienceLevelsUp() { void getWithInventoryReturnsDto() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); - var cacheManager = new ConcurrentMapCacheManager("characterGraph"); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); CharacterServiceImpl service = new CharacterServiceImpl( repo, mapper, - cacheManager, - meterRegistry, new PlayableStateKeyResolver(), new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); - service.initMetrics(); Character character = new Character(); character.setId(1L); @@ -85,11 +76,25 @@ void getWithInventoryReturnsDto() { character.setAccountId(1L); character.setPlayableStateKey("shared-live"); character.setName("Test"); + character.setActorIdentity( + ownerResolvedIdentity(1L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(repo.findWithInventoryById(1L)).thenReturn(Optional.of(character)); CharacterDto dto = service.getWithInventory(1L); assertEquals(1L, dto.id()); assertEquals(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, dto.playableStateScope()); + Mockito.verify(repo).findWithInventoryById(1L); + } + + private static ActorIdentity ownerResolvedIdentity(Long id, PlayableStateScope scope) { + return new ActorIdentity( + UUID.nameUUIDFromBytes(("character-" + id).getBytes()), + UUID.fromString("20000000-0000-4000-8000-000000000002"), + UUID.fromString("10000000-0000-4000-8000-000000000001"), + UUID.fromString("30000000-0000-4000-8000-000000000003"), + scope, + ActorIdentityStatus.OWNER_RESOLVED, + null); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java index b391495ef6..0d8cc614bf 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java @@ -20,6 +20,8 @@ import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; +import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -42,7 +44,7 @@ void listContainerContentsReturnsInstanceBackedDtos() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -94,7 +96,7 @@ void listContainerContentsReturnsStackBackedDtos() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -153,7 +155,7 @@ void putItemIntoContainerMovesSelectedInstancesIntoContainer() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -212,7 +214,7 @@ void putItemIntoContainerMovesStackQuantity() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -291,7 +293,7 @@ void takeItemFromContainerUsesExplicitItemInstanceId() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -349,7 +351,7 @@ void putItemIntoContainerRejectsNestedContainerViaSharedHolderPolicy() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -394,7 +396,7 @@ void putItemIntoContainerSelectsExplicitStackFamilyWhenMultipleFamiliesExist() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -469,6 +471,37 @@ private static Character character(Long id, Long tenantId) { return character; } + // These business-logic tests isolate item behavior after the scope guard. The mock only + // accepts a matching legacy playable-state key and is not owner-provenance proof. + private static ScopedCharacterResolver mockedScopedCharacterResolver( + CharacterRepository characterRepo) { + ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); + Mockito.when( + resolver.requireScopedCharacter( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.nullable(String.class), + Mockito.any(PlayableStateScope.class))) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + Long characterId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String playableStateKey = + new PlayableStateKeyResolver().resolve(gameInstanceId, scope); + Character character = + characterRepo + .findByIdAndTenantId(characterId, tenantId) + .orElseThrow(() -> new IllegalArgumentException("Character not found")); + if (!playableStateKey.equals(character.getPlayableStateKey())) { + throw new IllegalArgumentException("Test fixture playable-state scope mismatch"); + } + return character; + }); + return resolver; + } + private static Item item( Long id, Long tenantId, String name, boolean container, boolean stackable) { Item item = new Item(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java index 2715e33747..f3f564c766 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java @@ -22,6 +22,8 @@ import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.service.EquipmentSlotIncompatibleException; +import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -47,7 +49,7 @@ void listEquipmentReturnsInstanceBackedDtos() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -95,7 +97,7 @@ void wearItemMovesCarriedInstanceIntoSlot() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), itemTransferAuditWriter, @@ -156,7 +158,7 @@ void wearItemRejectsStaleSourceMismatch() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), itemTransferAuditWriter, @@ -203,7 +205,7 @@ void removeWornItemReturnsRemovedSlotWhileMovingItemIntoInventory() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), itemTransferAuditWriter, @@ -259,7 +261,7 @@ void removeWornItemRejectsStaleEquippedSourceMismatch() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -298,7 +300,7 @@ void wearItemRequiresAuthoredSlotWhenEquipmentSchemaExists() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -339,7 +341,7 @@ void wearItemRequiresBodyLayoutToSupportAuthoredSlot() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -387,7 +389,7 @@ void wearItemRequiresItemSlotGroupToMatchAuthoredSlotGroup() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - charRepo, + mockedScopedCharacterResolver(charRepo), itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -421,6 +423,37 @@ private static Character character(Long id, Long tenantId) { return character; } + // These business-logic tests isolate equipment behavior after the scope guard. The mock only + // accepts a matching legacy playable-state key and is not owner-provenance proof. + private static ScopedCharacterResolver mockedScopedCharacterResolver( + CharacterRepository characterRepo) { + ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); + Mockito.when( + resolver.requireScopedCharacter( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.nullable(String.class), + Mockito.any(PlayableStateScope.class))) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + Long characterId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String playableStateKey = + new PlayableStateKeyResolver().resolve(gameInstanceId, scope); + Character character = + characterRepo + .findByIdAndTenantId(characterId, tenantId) + .orElseThrow(() -> new IllegalArgumentException("Character not found")); + if (!playableStateKey.equals(character.getPlayableStateKey())) { + throw new IllegalArgumentException("Test fixture playable-state scope mismatch"); + } + return character; + }); + return resolver; + } + private static Item item( Long id, Long tenantId, String name, boolean container, String equipmentSlot) { Item item = new Item(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java index 4ca96c334a..9cb9627b3f 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java @@ -31,11 +31,28 @@ void setUp() { characterRepository = Mockito.mock(net.firedevops.firemud.entitymanagement.repository.CharacterRepository.class); CharacterFriendMapper mapper = Mappers.getMapper(CharacterFriendMapper.class); - service = - new FriendServiceImpl( - repository, - mapper, - new ScopedCharacterResolver(characterRepository, new PlayableStateKeyResolver())); + ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); + // These friend tests isolate relationship behavior after the playable-state scope guard; + // the fixture does not establish canonical owner provenance. + Mockito.when( + resolver.requireScopedCharacter( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class))) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + Long characterId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String playableStateKey = + new PlayableStateKeyResolver().resolve(gameInstanceId, scope); + return characterRepository + .findByIdAndTenantIdAndPlayableStateKey(characterId, tenantId, playableStateKey) + .orElseThrow(() -> new IllegalArgumentException("Character not found")); + }); + service = new FriendServiceImpl(repository, mapper, resolver); } @Test diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java index 5001e150c3..8abd296044 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java @@ -23,6 +23,8 @@ import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; +import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -885,7 +887,7 @@ private InventoryServiceImpl service( return new InventoryServiceImpl( itemInstanceRepo, containerInstanceRepo, - characterRepo, + mockedScopedCharacterResolver(characterRepo), itemRepo, itemStackRepo, visibleRefAllocator, @@ -895,6 +897,37 @@ private InventoryServiceImpl service( new StackableItemSupport()); } + // This collaborator mock keeps these inventory tests focused on item behavior after the + // playable-state scope guard. It does not provide owner-provenance or runtime identity proof. + private static ScopedCharacterResolver mockedScopedCharacterResolver( + CharacterRepository characterRepo) { + ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); + Mockito.when( + resolver.requireScopedCharacter( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.nullable(String.class), + Mockito.any(PlayableStateScope.class))) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + Long characterId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String playableStateKey = + new PlayableStateKeyResolver().resolve(gameInstanceId, scope); + Character character = + characterRepo + .findByIdAndTenantId(characterId, tenantId) + .orElseThrow(() -> new IllegalArgumentException("Character not found")); + if (!playableStateKey.equals(character.getPlayableStateKey())) { + throw new IllegalArgumentException("Test fixture playable-state scope mismatch"); + } + return character; + }); + return resolver; + } + private static Character character(Long id, Long tenantId) { Character character = new Character(); character.setId(id); From c53f14b0c4541bc47ee496069d5c84d140cfbea9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:12:17 +1300 Subject: [PATCH 02/39] Enforce persisted actor update identity and immutable namespace scope --- .../runtime-and-data.md | 4 +- .../gameplay-rules-entities-and-effects.md | 5 +- .../ActorActiveConditionRepository.java | 36 ++++-- .../ActorResourceStateRepository.java | 54 +++++--- .../QuarantinedActorRetentionRepository.java | 70 +++++----- .../RuntimeInstanceCleanupServiceImpl.java | 39 +----- ...__quarantine_unresolved_actor_identity.sql | 57 ++++++--- ...ld_actor_identity_indexes_concurrently.sql | 20 +++ ...tor_identity_indexes_concurrently.sql.conf | 1 + ...4__validate_actor_identity_constraints.sql | 33 +++++ .../RetainedActorIdentityIntegrationTest.java | 113 ++++++++++++++++- .../ActorActiveConditionRepositoryTest.java | 120 ++++++++++++++++++ .../ActorResourceStateRepositoryTest.java | 117 +++++++++++++++++ ...arantinedActorRetentionRepositoryTest.java | 89 +++++++++++++ ...RuntimeInstanceCleanupServiceImplTest.java | 58 +++++++++ 15 files changed, 687 insertions(+), 129 deletions(-) create mode 100644 services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf create mode 100644 services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index ae8cbac8ec..a60d825067 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -17,7 +17,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. - Legacy character roster/name reads return no actors, numeric-ID graph reads require a fresh persisted `OWNER_RESOLVED` row and bypass the old character graph cache, and scoped gameplay resolution fails closed instead of translating `shared-live` or `instance:`. Consequently, production scoped inventory, containment, equipment, friend, and actor-state/effect calls do not admit legacy actor identities; no canonical owner-qualified gameplay admission path is connected. Resource/condition repositories additionally gate retained rows by actor disposition, and quarantined conditions are excluded from expiry. Conditional service and holder-persistence tests exercise downstream behavior only after an explicitly mocked test guard and do not prove owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. -- Runtime-instance cleanup now refuses to acknowledge cleanup while the target `(tenantId, gameInstanceId)` still contains item instances, containers, stacks, or room-ground rows, because those legacy families lack owner-resolved namespace/scope classification and may not be assumed S3. A quarantined-actor-linked transfer audit also holds cleanup. The check covers the actual target runtime holder set and its nested closure; it does not infer a character association from the runtime pointer, relabel room-ground rows, or delete audits/replay receipts. Empty-target cleanup does not establish that nonempty legacy families are safe to dispose. +- Runtime-instance cleanup treats any target `(tenantId, gameInstanceId)` item-instance, container, item-stack, or room-ground row as unclassified evidence and holds cleanup; legacy holder families lack namespace and disposal provenance, so no row is associated with an actor or classified as disposable from a runtime pointer. A transfer audit also holds cleanup when its existing actor link identifies a quarantined actor and its source or destination runtime matches the target. The typed read uses one tenant/runtime target pair and fails closed if its Boolean result is unavailable. An observed empty target returns zero deletion counts and issues no family deletes; this is only an empty-target observation, not trusted quiescence or authority to dispose a nonempty target. Nonempty cleanup remains closed pending owner classification and a fence. This observation-only boundary avoids a check/delete race from deleting rows after the check. - `characters` still retains the legacy private numeric account/tenant IDs and `playable_state_key`; only the canonical actor provenance columns are UUID-shaped. `actor_resource_states` also retains legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and holder/containment rows do not yet carry `playableStateNamespaceId` (and some omit `tenant_id`). Those dependent families therefore do not yet enforce target `{tenantUuid, playableStateNamespaceId, domainObjectId}` identity. V2 preserves them without inferred mapping; canonical dependent-row migration and owner-backed namespace isolation remain open. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. - `getWithInventory(characterId)` no longer reads from or populates the legacy `characterGraph` cache; it always performs a fresh persisted `OWNER_RESOLVED` read, so stale cache entries cannot authorize a response. The old ID-only cache has no namespace or authoritative-version validation and must not be reconnected as correctness authority; the target namespace-qualified Class A `character-cache:*` contract remains unimplemented. @@ -419,7 +419,7 @@ Operators and later fraud/dupe-detection tooling should also be able to derive l Synthetic room-ground containers scoped by `(tenantId, gameInstanceId, roomInstanceId)` must be removed through the durable Temporal `world-lifecycle` termination flow described in World Management docs: - Game Session must already have closed admissions for the target instance before cleanup starts. -- Entity Management owns cleanup of containers and contained items for a terminating `gameInstanceId`. +- Entity Management owns cleanup of containers and contained items for a terminating `gameInstanceId`; the current implementation cannot authorize deletion of nonempty legacy holder families until their owner classification and cleanup fence are established. - Cleanup must be idempotent and guarded by a durable workflow step key so retries converge without double-deletes. - Entity Management must not treat world row deletion as implicit cleanup confirmation; World Management marks an instance `TERMINATED` only after this service confirms cleanup completion. - Entity Management must register every additional `gameInstanceId`-owned family, its S3 classification, cleanup request identity, retention rule, and acknowledgement status with the lifecycle owner. Missing or unregistered Entity families block `TERMINATED`; cleanup of one known room-ground family is not whole-service completion. Namespace-backed S1/S2 state under `(tenantId, playableStateNamespaceId)` plus its domain object identity is retained or mapped under the replacement contract; the immutable `playableStateScope` remains separately validated and must not be reinterpreted, and that state is not deleted merely because one runtime instance ended. See [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 7b07280f43..4cea2611e5 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,7 +26,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `partial` - `ActorIdentityValueTest` passed 3/3; `RetainedActorIdentityIntegrationTest` compiled but all 4 PostgreSQL-backed cases were skipped because Docker is unavailable. The migration/SQL-isolation assertions are authored, not executed; fixture-created `OWNER_RESOLVED` rows prove SQL predicates only, not owner-backed runtime provenance. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `partial` - The full Entity unit task passed 203 tests with zero failures/errors/skips, including persisted-row update guards and observation-only cleanup. Five `RetainedActorIdentityIntegrationTest` PostgreSQL cases compiled but are unexecuted on the corrected V2–V4 chain because local Docker is disabled. The migration/SQL-isolation assertions are authored, not executed; fixture-created `OWNER_RESOLVED` rows test SQL predicates only, not owner-backed runtime provenance. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `partial` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `partial` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `partial` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | @@ -126,7 +126,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); pending generated-child allocation is recorded only in the non-authoritative [ADR 0183 proposal](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. - [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md) and [ADR 0061](../../architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md) keep ambient/location facts in World, item holders in Entity, and root outcomes/reconciliation in Game Session. Current gameplay has no complete cross-owner mutation/targeting proof; the accepted ownership direction does not promote current item or movement seams. -- Reachable tenant-access-checked administrative `POST`/`DELETE` inventory/equipment mutation handlers persist `ItemInstance` and `ItemStack` through Entity outside Game Session effect, tick, and barrier admission and do not require character ownership. `ScopedCharacterResolver` verifies tenant, character, and playable-state scope; persistence outside Game Session admission remains a gap. The current paths do not establish an admin-role check or an approved owner/admin contract. +- Guarded administrative inventory/equipment mutation handlers require scoped actor resolution, which unconditionally denies legacy actor identities before persistence; these guarded paths cannot currently write `ItemInstance` or `ItemStack`. They remain outside Game Session effect, tick, and barrier admission, and the code does not establish an approved owner/admin contract. +- Separately, the crafting REST adapter remains runtime-reachable unsupported implementation drift: it lacks tenant binding and trusts request-supplied tenant and item identifiers. The details and target boundary remain in [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). - Broader gameplay families remain unimplemented or unproved against the target contracts owned by [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and the canonical [Transactions generated-effect-chain contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The parent inventory slice remains partially implemented as a domain: manual happy-path verification over both WebSocket and Telnet is still unchecked, and later nested-container UX, crafting/material flows, banking/vendor/mail/trade, loot generation, scripted item behavior, durability, and richer client filtering are not implemented. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java index 6863e9ed80..c319b84651 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java @@ -92,18 +92,30 @@ public ActorActiveCondition save(ActorActiveCondition entity) { entity.setId(id); return entity; } - dsl.update(ACTOR_ACTIVE_CONDITIONS) - .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) - .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) - .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.VERSION, entity.getVersion() + 1) - .where(ACTOR_ACTIVE_CONDITIONS.ID.eq(entity.getId())) - .execute(); + int updatedRows = + dsl.update(ACTOR_ACTIVE_CONDITIONS) + .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) + .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) + .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) + .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) + .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) + .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) + .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) + .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + .set(ACTOR_ACTIVE_CONDITIONS.VERSION, entity.getVersion() + 1) + .where( + ACTOR_ACTIVE_CONDITIONS + .ID + .eq(entity.getId()) + .and(ACTOR_ACTIVE_CONDITIONS.TENANT_ID.eq(entity.getTenantId())) + .and( + ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(entity.getPlayableStateKey())) + .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(entity.getCharacterId())) + .and(ownerResolvedActorExists())) + .execute(); + if (updatedRows != 1) { + throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + } entity.setVersion(entity.getVersion() + 1); return entity; } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 2c7064cecd..7cf103b979 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java @@ -32,16 +32,7 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO .eq(tenantId) .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId)) - .and( - DSL.exists( - dsl.selectOne() - .from(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(ACTOR_RESOURCE_STATES.CHARACTER_ID) - .and(CHARACTERS.TENANT_ID.eq(ACTOR_RESOURCE_STATES.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))))) + .and(ownerResolvedActorExists())) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } @@ -67,16 +58,27 @@ public ActorResourceState save(ActorResourceState entity) { entity.setId(id); return entity; } - dsl.update(ACTOR_RESOURCE_STATES) - .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) - .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) - .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) - .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) - .set(ACTOR_RESOURCE_STATES.VERSION, entity.getVersion() + 1) - .where(ACTOR_RESOURCE_STATES.ID.eq(entity.getId())) - .execute(); + int updatedRows = + dsl.update(ACTOR_RESOURCE_STATES) + .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) + .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) + .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) + .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) + .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) + .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + .set(ACTOR_RESOURCE_STATES.VERSION, entity.getVersion() + 1) + .where( + ACTOR_RESOURCE_STATES + .ID + .eq(entity.getId()) + .and(ACTOR_RESOURCE_STATES.TENANT_ID.eq(entity.getTenantId())) + .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(entity.getPlayableStateKey())) + .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(entity.getCharacterId())) + .and(ownerResolvedActorExists())) + .execute(); + if (updatedRows != 1) { + throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + } entity.setVersion(entity.getVersion() + 1); return entity; } @@ -95,6 +97,18 @@ private void requireOwnerResolvedActor(Long tenantId, Long characterId) { } } + private org.jooq.Condition ownerResolvedActorExists() { + return DSL.exists( + dsl.selectOne() + .from(CHARACTERS) + .where( + CHARACTERS + .ID + .eq(ACTOR_RESOURCE_STATES.CHARACTER_ID) + .and(CHARACTERS.TENANT_ID.eq(ACTOR_RESOURCE_STATES.TENANT_ID)) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + } + private ActorResourceState toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java index fc49b7be18..eea689b28b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java @@ -2,40 +2,50 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; -/** Holds ambiguous runtime evidence and quarantined-actor closure before instance cleanup. */ +/** Detects unclassified runtime rows and quarantined-actor audit evidence before cleanup. */ @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class QuarantinedActorRetentionRepository { - private static final String HAS_UNRESOLVED_RUNTIME_EVIDENCE_SQL = + private static final String HAS_UNCLASSIFIED_OR_QUARANTINED_RUNTIME_EVIDENCE_SQL = """ + WITH target AS ( + SELECT CAST(? AS BIGINT) AS tenant_id, + CAST(? AS TEXT) AS game_instance_id + ) SELECT - EXISTS ( + CAST((EXISTS ( SELECT 1 FROM item_instances item_instance - WHERE item_instance.tenant_id = ? - AND item_instance.game_instance_id = ? + CROSS JOIN target + WHERE item_instance.tenant_id = target.tenant_id + AND item_instance.game_instance_id = target.game_instance_id ) OR EXISTS ( SELECT 1 FROM container_instances container - WHERE container.tenant_id = ? - AND container.game_instance_id = ? + CROSS JOIN target + WHERE container.tenant_id = target.tenant_id + AND container.game_instance_id = target.game_instance_id ) OR EXISTS ( SELECT 1 FROM item_stacks stack - WHERE stack.tenant_id = ? - AND stack.game_instance_id = ? + CROSS JOIN target + WHERE stack.tenant_id = target.tenant_id + AND stack.game_instance_id = target.game_instance_id ) OR EXISTS ( SELECT 1 FROM room_ground_inventory ground - WHERE ground.tenant_id = ? - AND ground.game_instance_id = ? + CROSS JOIN target + WHERE ground.tenant_id = target.tenant_id + AND ground.game_instance_id = target.game_instance_id ) OR EXISTS ( SELECT 1 @@ -48,12 +58,13 @@ OR EXISTS ( OR actor.id = audit.source_character_id OR actor.id = audit.destination_character_id ) - WHERE audit.tenant_id = ? + CROSS JOIN target + WHERE audit.tenant_id = target.tenant_id AND ( - audit.source_game_instance_id = ? - OR audit.destination_game_instance_id = ? + audit.source_game_instance_id = target.game_instance_id + OR audit.destination_game_instance_id = target.game_instance_id ) - ) + )) AS BOOLEAN) """; private final DSLContext dsl; @@ -62,21 +73,18 @@ public QuarantinedActorRetentionRepository(DSLContext dsl) { this.dsl = dsl; } - public boolean hasUnresolvedRuntimeEvidence(Long tenantId, String gameInstanceId) { - Object retained = - dsl.fetchValue( - HAS_UNRESOLVED_RUNTIME_EVIDENCE_SQL, - tenantId, - gameInstanceId, - tenantId, - gameInstanceId, - tenantId, - gameInstanceId, - tenantId, - gameInstanceId, - tenantId, - gameInstanceId, - gameInstanceId); - return Boolean.TRUE.equals(retained); + public boolean hasUnclassifiedOrQuarantinedRuntimeEvidence(Long tenantId, String gameInstanceId) { + Record result = + dsl.fetchOne( + DSL.sql( + HAS_UNCLASSIFIED_OR_QUARANTINED_RUNTIME_EVIDENCE_SQL, tenantId, gameInstanceId)); + if (result == null) { + throw new IllegalStateException("RUNTIME_EVIDENCE_READBACK_UNAVAILABLE"); + } + Boolean retained = result.get(0, Boolean.class); + if (retained == null) { + throw new IllegalStateException("RUNTIME_EVIDENCE_READBACK_UNAVAILABLE"); + } + return retained; } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java index 6c82d47d19..41f3ceea4b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java @@ -1,37 +1,17 @@ package net.firedevops.firemud.entitymanagement.service.impl; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import net.firedevops.firemud.entitymanagement.dto.RuntimeInstanceCleanupResultDto; -import net.firedevops.firemud.entitymanagement.repository.ContainerInstanceRepository; -import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; -import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; -import net.firedevops.firemud.entitymanagement.repository.RoomGroundInventoryRepository; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected repositories are managed dependencies kept internal.") public class RuntimeInstanceCleanupServiceImpl implements RuntimeInstanceCleanupService { - private final RoomGroundInventoryRepository roomGroundInventoryRepository; - private final ItemStackRepository itemStackRepository; - private final ItemInstanceRepository itemInstanceRepository; - private final ContainerInstanceRepository containerInstanceRepository; private final QuarantinedActorRetentionRepository quarantinedActorRetentionRepository; public RuntimeInstanceCleanupServiceImpl( - RoomGroundInventoryRepository roomGroundInventoryRepository, - ItemStackRepository itemStackRepository, - ItemInstanceRepository itemInstanceRepository, - ContainerInstanceRepository containerInstanceRepository, QuarantinedActorRetentionRepository quarantinedActorRetentionRepository) { - this.roomGroundInventoryRepository = roomGroundInventoryRepository; - this.itemStackRepository = itemStackRepository; - this.itemInstanceRepository = itemInstanceRepository; - this.containerInstanceRepository = containerInstanceRepository; this.quarantinedActorRetentionRepository = quarantinedActorRetentionRepository; } @@ -48,24 +28,11 @@ public RuntimeInstanceCleanupResultDto cleanupRuntimeInstance( if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } - if (quarantinedActorRetentionRepository.hasUnresolvedRuntimeEvidence( + if (quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( tenantId, gameInstanceId)) { throw new IllegalStateException( - "ENTITY_RETAINED_ACTOR_EVIDENCE_BLOCKS_CLEANUP: runtime holder ownership or quarantined actor audit evidence is unresolved"); + "ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP: runtime rows lack owner classification or quarantined actor audit evidence is present"); } - long deletedRoomGroundEntries = - roomGroundInventoryRepository.deleteByIdTenantIdAndIdGameInstanceId( - tenantId, gameInstanceId); - long deletedItemStacks = - itemStackRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); - long deletedItemInstances = - itemInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); - long deletedContainerInstances = - containerInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); - return new RuntimeInstanceCleanupResultDto( - deletedRoomGroundEntries, - deletedItemStacks, - deletedItemInstances, - deletedContainerInstances); + return new RuntimeInstanceCleanupResultDto(0, 0, 0, 0); } } diff --git a/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql b/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql index fa0d31a2cf..2022ded057 100644 --- a/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql +++ b/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql @@ -18,6 +18,29 @@ CREATE TABLE entity_playable_state_namespace_scopes ( UNIQUE (tenant_uuid, playable_state_namespace_id, playable_state_scope) ); +/* [jooq ignore start] */ +CREATE FUNCTION reject_entity_playable_state_namespace_scope_change() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.tenant_uuid, NEW.playable_state_namespace_id, NEW.playable_state_scope) + IS DISTINCT FROM + (OLD.tenant_uuid, OLD.playable_state_namespace_id, OLD.playable_state_scope) THEN + RAISE EXCEPTION 'entity playable-state namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_playable_state_namespace_scopes_immutable + BEFORE UPDATE OF tenant_uuid, playable_state_namespace_id, playable_state_scope + ON entity_playable_state_namespace_scopes + FOR EACH ROW + EXECUTE FUNCTION reject_entity_playable_state_namespace_scope_change(); +/* [jooq ignore stop] */ + ALTER TABLE characters ADD COLUMN character_uuid UUID, ADD COLUMN account_uuid UUID, @@ -32,22 +55,23 @@ UPDATE characters SET character_uuid = gen_random_uuid(), actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING'; +-- This retained-row backfill updates every existing character in one migration transaction. +-- Quiesce Entity character writes for this migration; it is not an online activation procedure. ALTER TABLE characters ALTER COLUMN character_uuid SET DEFAULT gen_random_uuid(); +/* [jooq ignore start] */ ALTER TABLE characters - ALTER COLUMN character_uuid SET NOT NULL; - -ALTER TABLE characters - ADD CONSTRAINT ux_characters_character_uuid UNIQUE (character_uuid); + ADD CONSTRAINT ck_characters_character_uuid_nonnull + CHECK (character_uuid IS NOT NULL) NOT VALID; ALTER TABLE characters ADD CONSTRAINT ck_characters_character_uuid_non_nil - CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID); + CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) NOT VALID; ALTER TABLE characters ADD CONSTRAINT ck_characters_actor_identity_status - CHECK (actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED')); + CHECK (actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED')) NOT VALID; ALTER TABLE characters ADD CONSTRAINT ck_characters_actor_identity_quarantine_reason @@ -57,7 +81,7 @@ ALTER TABLE characters AND length(trim(actor_identity_quarantine_reason)) > 0) OR (actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL) - ); + ) NOT VALID; ALTER TABLE characters ADD CONSTRAINT ck_characters_actor_identity_uuid_non_nil @@ -65,7 +89,7 @@ ALTER TABLE characters (account_uuid IS NULL OR account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) AND (tenant_uuid IS NULL OR tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) AND (playable_state_namespace_id IS NULL OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID) - ); + ) NOT VALID; ALTER TABLE characters ADD CONSTRAINT ck_characters_actor_identity_scope @@ -75,7 +99,7 @@ ALTER TABLE characters 'PLAYABLE_STATE_SCOPE_SHARED', 'PLAYABLE_STATE_SCOPE_ISOLATED' ) - ); + ) NOT VALID; ALTER TABLE characters ADD CONSTRAINT ck_characters_owner_resolved_provenance @@ -87,7 +111,7 @@ ALTER TABLE characters AND playable_state_namespace_id IS NOT NULL AND playable_state_scope IS NOT NULL ) - ); + ) NOT VALID; ALTER TABLE characters ADD CONSTRAINT fk_characters_owner_resolved_namespace_scope @@ -96,17 +120,8 @@ ALTER TABLE characters tenant_uuid, playable_state_namespace_id, playable_state_scope - ); - -CREATE INDEX idx_characters_owner_resolved_roster - ON characters ( - tenant_uuid, - account_uuid, - playable_state_namespace_id, - playable_state_scope, - character_uuid - ) - WHERE actor_identity_status = 'OWNER_RESOLVED'; + ) NOT VALID; +/* [jooq ignore stop] */ /* [jooq ignore start] */ CREATE VIEW entity_quarantined_actor_item_instances AS diff --git a/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql b/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql new file mode 100644 index 0000000000..da86ec481a --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql @@ -0,0 +1,20 @@ +/* [jooq ignore start] */ +CREATE UNIQUE INDEX CONCURRENTLY ux_characters_character_uuid_idx + ON characters (character_uuid); + +CREATE INDEX CONCURRENTLY idx_characters_owner_resolved_roster + ON characters ( + tenant_uuid, + account_uuid, + playable_state_namespace_id, + playable_state_scope, + character_uuid + ) + WHERE actor_identity_status = 'OWNER_RESOLVED'; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +ALTER TABLE characters + ADD CONSTRAINT ux_characters_character_uuid + UNIQUE USING INDEX ux_characters_character_uuid_idx; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf b/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf new file mode 100644 index 0000000000..73bd53a146 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf @@ -0,0 +1 @@ +executeInTransaction=false diff --git a/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql b/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql new file mode 100644 index 0000000000..97eb17a563 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql @@ -0,0 +1,33 @@ +/* [jooq ignore start] */ +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull; +/* [jooq ignore stop] */ + +ALTER TABLE characters + ALTER COLUMN character_uuid SET NOT NULL; + +/* [jooq ignore start] */ +ALTER TABLE characters + DROP CONSTRAINT ck_characters_character_uuid_nonnull; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_character_uuid_non_nil; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_status; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_quarantine_reason; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_uuid_non_nil; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_scope; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_owner_resolved_provenance; + +ALTER TABLE characters + VALIDATE CONSTRAINT fk_characters_owner_resolved_namespace_scope; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 7e0800a2c9..0b9b2a1e93 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -262,6 +262,72 @@ void canonicalRosterIsExactOrderedAndExcludesLegacyQuarantine() { .isInstanceOf(RuntimeException.class); } + @Test + void namespaceIdentityAndScopeAreImmutableWithoutActorReferences() { + for (PlayableStateScope scope : + new PlayableStateScope[] { + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + }) { + UUID tenantUuid = UUID.randomUUID(); + UUID namespaceUuid = UUID.randomUUID(); + UUID changedTenantUuid = UUID.randomUUID(); + UUID changedNamespaceUuid = UUID.randomUUID(); + PlayableStateScope changedScope = + scope == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + ? PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + : PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + insertNamespace(tenantUuid, namespaceUuid, scope); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + Integer.class, + tenantUuid, + namespaceUuid)) + .isZero(); + assertThat( + jdbcTemplate.update( + "UPDATE entity_playable_state_namespace_scopes " + + "SET tenant_uuid = ?, playable_state_namespace_id = ?, playable_state_scope = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + tenantUuid, + namespaceUuid, + scope.name(), + tenantUuid, + namespaceUuid)) + .isOne(); + + assertNamespaceIdentityUpdateRejected( + "UPDATE entity_playable_state_namespace_scopes SET tenant_uuid = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + changedTenantUuid, + tenantUuid, + namespaceUuid); + assertNamespaceIdentityUpdateRejected( + "UPDATE entity_playable_state_namespace_scopes SET playable_state_namespace_id = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + changedNamespaceUuid, + tenantUuid, + namespaceUuid); + assertNamespaceIdentityUpdateRejected( + "UPDATE entity_playable_state_namespace_scopes SET playable_state_scope = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + changedScope.name(), + tenantUuid, + namespaceUuid); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + String.class, + tenantUuid, + namespaceUuid)) + .isEqualTo(scope.name()); + } + } + @Test void quarantinedActorLookupMutationExpiryAndCleanupRemainHeld() { Character actor = new Character(); @@ -398,10 +464,10 @@ void quarantinedActorLookupMutationExpiryAndCleanupRemainHeld() { runtimeInstanceCleanupService.cleanupRuntimeInstance( TENANT_ID, INSTANCE_ID, "termination-retained")) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_RETAINED_ACTOR_EVIDENCE_BLOCKS_CLEANUP"); + .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); assertThat( - quarantinedActorRetentionRepository.hasUnresolvedRuntimeEvidence( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( TENANT_ID, INSTANCE_ID)) .isTrue(); assertThat( @@ -516,7 +582,7 @@ void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { INSTANCE_ID); assertThat( - quarantinedActorRetentionRepository.hasUnresolvedRuntimeEvidence( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( TENANT_ID, INSTANCE_ID)) .isTrue(); assertThatThrownBy( @@ -524,7 +590,7 @@ void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { runtimeInstanceCleanupService.cleanupRuntimeInstance( TENANT_ID, INSTANCE_ID, "termination-unresolved-ground")) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_RETAINED_ACTOR_EVIDENCE_BLOCKS_CLEANUP"); + .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); assertThat( jdbcTemplate.queryForObject( "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", @@ -535,7 +601,7 @@ void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { } @Test - void flywayV1ToV2RetainsLegacyRowsAndEveryDependentStateFamily() throws SQLException { + void flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLException { migrateLegacySchemaToV1(); try (Connection connection = connectToMigrationSchema()) { var statement = connection.createStatement(); @@ -578,6 +644,38 @@ void flywayV1ToV2RetainsLegacyRowsAndEveryDependentStateFamily() throws SQLExcep try (Connection connection = connectToMigrationSchema(); var statement = connection.createStatement()) { + assertThat( + readLong( + statement, + "SELECT count(*) FROM pg_constraint " + + "WHERE conrelid = 'characters'::regclass AND convalidated " + + "AND conname IN ('ck_characters_actor_identity_status', " + + "'ck_characters_actor_identity_quarantine_reason', " + + "'ck_characters_actor_identity_uuid_non_nil', " + + "'ck_characters_actor_identity_scope', " + + "'ck_characters_owner_resolved_provenance', " + + "'fk_characters_owner_resolved_namespace_scope', " + + "'ck_characters_character_uuid_non_nil', " + + "'ux_characters_character_uuid')")) + .isEqualTo(8L); + assertThat( + readLong( + statement, + "SELECT count(*) FROM pg_index indexes " + + "JOIN pg_class index_relation ON index_relation.oid = indexes.indexrelid " + + "JOIN pg_namespace index_schema ON index_schema.oid = index_relation.relnamespace " + + "WHERE index_schema.nspname = current_schema() " + + "AND index_relation.relname IN ('ux_characters_character_uuid', " + + "'idx_characters_owner_resolved_roster') " + + "AND indexes.indisvalid AND indexes.indisready")) + .isEqualTo(2L); + assertThat( + readLong( + statement, + "SELECT count(*) FROM pg_attribute " + + "WHERE attrelid = 'characters'::regclass AND attname = 'character_uuid' " + + "AND attnotnull AND NOT attisdropped")) + .isEqualTo(1L); try (var rows = statement.executeQuery( "SELECT id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason FROM characters ORDER BY id")) { @@ -747,6 +845,11 @@ private void insertNamespace(UUID tenantUuid, UUID namespaceUuid, PlayableStateS scope.name()); } + private void assertNamespaceIdentityUpdateRejected(String sql, Object... arguments) { + assertThatThrownBy(() -> jdbcTemplate.update(sql, arguments)) + .hasMessageContaining("entity playable-state namespace identity is immutable"); + } + private long insertActor( String name, UUID characterUuid, diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java new file mode 100644 index 0000000000..1259a124fd --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record1; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class ActorActiveConditionRepositoryTest { + private static final Long ROW_ID = 71L; + private static final Long TENANT_ID = 13L; + private static final String PLAYABLE_STATE_KEY = "world:scope:4"; + private static final Long CHARACTER_ID = 29L; + + @Test + void saveUpdateUsesPersistedIdentityPredicatesAndOwnerResolvedGuard() { + AtomicReference updateSql = new AtomicReference<>(); + AtomicReference updateBindings = new AtomicReference<>(); + MockDataProvider provider = providerForUpdate(1, updateSql, updateBindings); + ActorActiveConditionRepository repository = repository(provider); + var entity = condition(); + + repository.save(entity); + + String sql = updateSql.get().toLowerCase(Locale.ROOT); + String whereClause = sql.substring(sql.indexOf(" where ")).replaceAll("\\s+", " "); + assertThat(whereClause) + .contains( + "\"id\" = ?", + "\"tenant_id\" = ?", + "\"playable_state_key\" = ?", + "\"character_id\" = ?", + "exists (select 1", + "\"actor_identity_status\" = ?"); + assertThat(Arrays.asList(updateBindings.get())) + .contains(ROW_ID, TENANT_ID, PLAYABLE_STATE_KEY, CHARACTER_ID, "OWNER_RESOLVED"); + assertThat(entity.getVersion()).isEqualTo(5); + } + + @Test + void saveUpdateWithZeroRowsFailsWithoutChangingVersion() { + ActorActiveCondition entity = condition(); + assertUpdateFailure(entity, 0); + } + + @Test + void saveUpdateWithMultipleRowsFailsWithoutChangingVersion() { + ActorActiveCondition entity = condition(); + assertUpdateFailure(entity, 2); + } + + private static void assertUpdateFailure(ActorActiveCondition entity, int updatedRows) { + ActorActiveConditionRepository repository = + repository( + providerForUpdate(updatedRows, new AtomicReference<>(), new AtomicReference<>())); + + assertThatThrownBy(() -> repository.save(entity)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + assertThat(entity.getVersion()).isEqualTo(4); + } + + private static MockDataProvider providerForUpdate( + int updatedRows, + AtomicReference updateSql, + AtomicReference updateBindings) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + Field countField = DSL.field("count", Integer.class); + Record1 countRow = resultDsl.newRecord(countField); + countRow.set(countField, 1); + Result> countResult = resultDsl.newResult(countField); + countResult.add(countRow); + return context -> { + String sql = context.sql().trim(); + if (sql.toLowerCase(Locale.ROOT).startsWith("update")) { + updateSql.set(sql); + updateBindings.set(context.bindings()); + return new MockResult[] {new MockResult(updatedRows)}; + } + return new MockResult[] {new MockResult(1, countResult)}; + }; + } + + private static ActorActiveConditionRepository repository(MockDataProvider provider) { + return new ActorActiveConditionRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + } + + private static ActorActiveCondition condition() { + var entity = new ActorActiveCondition(); + entity.setId(ROW_ID); + entity.setTenantId(TENANT_ID); + entity.setPlayableStateKey(PLAYABLE_STATE_KEY); + entity.setCharacterId(CHARACTER_ID); + entity.setConditionKey("condition-unique"); + entity.setStackCount(3); + entity.setSourceType("source-unique"); + entity.setSourceId("source-id-unique"); + entity.setStartedAt(Instant.parse("2024-01-01T00:00:00Z")); + entity.setExpiresAt(Instant.parse("2024-01-02T00:00:00Z")); + entity.setEffectPayloadJson("{\"unique\":true}"); + entity.setCreatedAt(Instant.parse("2024-01-03T00:00:00Z")); + entity.setUpdatedAt(Instant.parse("2024-01-04T00:00:00Z")); + entity.setVersion(4); + return entity; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java new file mode 100644 index 0000000000..80e3187ffb --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record1; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class ActorResourceStateRepositoryTest { + private static final Long ROW_ID = 83L; + private static final Long TENANT_ID = 17L; + private static final String PLAYABLE_STATE_KEY = "realm:state:9"; + private static final Long CHARACTER_ID = 37L; + + @Test + void saveUpdateUsesPersistedIdentityPredicatesAndOwnerResolvedGuard() { + AtomicReference updateSql = new AtomicReference<>(); + AtomicReference updateBindings = new AtomicReference<>(); + ActorResourceStateRepository repository = + repository(providerForUpdate(1, updateSql, updateBindings)); + var entity = state(); + + repository.save(entity); + + String sql = updateSql.get().toLowerCase(Locale.ROOT); + String whereClause = sql.substring(sql.indexOf(" where ")).replaceAll("\\s+", " "); + assertThat(whereClause) + .contains( + "\"id\" = ?", + "\"tenant_id\" = ?", + "\"playable_state_key\" = ?", + "\"character_id\" = ?", + "exists (select 1", + "\"actor_identity_status\" = ?"); + assertThat(Arrays.asList(updateBindings.get())) + .contains(ROW_ID, TENANT_ID, PLAYABLE_STATE_KEY, CHARACTER_ID, "OWNER_RESOLVED"); + assertThat(entity.getVersion()).isEqualTo(6); + } + + @Test + void saveUpdateWithZeroRowsFailsWithoutChangingVersion() { + assertUpdateFailure(state(), 0); + } + + @Test + void saveUpdateWithMultipleRowsFailsWithoutChangingVersion() { + assertUpdateFailure(state(), 2); + } + + private static void assertUpdateFailure(ActorResourceState entity, int updatedRows) { + ActorResourceStateRepository repository = + repository( + providerForUpdate(updatedRows, new AtomicReference<>(), new AtomicReference<>())); + + assertThatThrownBy(() -> repository.save(entity)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + assertThat(entity.getVersion()).isEqualTo(5); + } + + private static MockDataProvider providerForUpdate( + int updatedRows, + AtomicReference updateSql, + AtomicReference updateBindings) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + Field countField = DSL.field("count", Integer.class); + Record1 countRow = resultDsl.newRecord(countField); + countRow.set(countField, 1); + Result> countResult = resultDsl.newResult(countField); + countResult.add(countRow); + return context -> { + String sql = context.sql().trim(); + if (sql.toLowerCase(Locale.ROOT).startsWith("update")) { + updateSql.set(sql); + updateBindings.set(context.bindings()); + return new MockResult[] {new MockResult(updatedRows)}; + } + return new MockResult[] {new MockResult(1, countResult)}; + }; + } + + private static ActorResourceStateRepository repository(MockDataProvider provider) { + return new ActorResourceStateRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + } + + private static ActorResourceState state() { + var entity = new ActorResourceState(); + entity.setId(ROW_ID); + entity.setTenantId(TENANT_ID); + entity.setPlayableStateKey(PLAYABLE_STATE_KEY); + entity.setCharacterId(CHARACTER_ID); + entity.setStatKey("resource-unique"); + entity.setCurrentValue(11L); + entity.setMaxValue(19L); + entity.setBaseValue(23L); + entity.setSourceType("source-unique"); + entity.setSourceId("source-id-unique"); + entity.setCreatedAt(Instant.parse("2024-02-01T00:00:00Z")); + entity.setUpdatedAt(Instant.parse("2024-02-02T00:00:00Z")); + entity.setVersion(5); + return entity; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java new file mode 100644 index 0000000000..f54733cc89 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Arrays; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicReference; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record1; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class QuarantinedActorRetentionRepositoryTest { + private static final Long TENANT_ID = 29L; + private static final String GAME_INSTANCE_ID = "runtime-opaque"; + + @Test + void readsTypedBooleanWithOneTargetBindingPairAndHoldsRowsNeedingClassification() { + AtomicReference sqlRead = new AtomicReference<>(); + AtomicReference bindingsRead = new AtomicReference<>(); + QuarantinedActorRetentionRepository repository = repository(true, sqlRead, bindingsRead); + + assertThat(repository.hasUnclassifiedOrQuarantinedRuntimeEvidence(TENANT_ID, GAME_INSTANCE_ID)) + .isTrue(); + + String sql = sqlRead.get().toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); + assertThat(sql) + .contains("with target as") + .contains("cast(? as bigint)") + .contains("cast(? as text)") + .contains("from item_instances item_instance") + .contains("from container_instances container") + .contains("from item_stacks stack") + .contains("from room_ground_inventory ground") + .contains("actor.actor_identity_status = 'quarantined'") + .contains("audit.source_game_instance_id = target.game_instance_id") + .contains("audit.destination_game_instance_id = target.game_instance_id") + .contains("as boolean)"); + assertThat(Arrays.asList(bindingsRead.get())).containsExactly(TENANT_ID, GAME_INSTANCE_ID); + } + + @Test + void falseBooleanReportsNoObservedUnclassifiedOrQuarantinedEvidence() { + QuarantinedActorRetentionRepository repository = repository(false, null, null); + + assertThat(repository.hasUnclassifiedOrQuarantinedRuntimeEvidence(TENANT_ID, GAME_INSTANCE_ID)) + .isFalse(); + } + + @Test + void nullBooleanReadbackFailsClosed() { + QuarantinedActorRetentionRepository repository = repository(null, null, null); + + assertThatThrownBy( + () -> + repository.hasUnclassifiedOrQuarantinedRuntimeEvidence(TENANT_ID, GAME_INSTANCE_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("RUNTIME_EVIDENCE_READBACK_UNAVAILABLE"); + } + + private static QuarantinedActorRetentionRepository repository( + Boolean readback, AtomicReference sqlRead, AtomicReference bindingsRead) { + MockDataProvider provider = + context -> { + if (sqlRead != null) { + sqlRead.set(context.sql()); + } + if (bindingsRead != null) { + bindingsRead.set(context.bindings()); + } + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + Field retainedField = DSL.field("retained", Boolean.class); + Record1 row = resultDsl.newRecord(retainedField); + row.set(retainedField, readback); + Result> result = resultDsl.newResult(retainedField); + result.add(row); + return new MockResult[] {new MockResult(1, result)}; + }; + return new QuarantinedActorRetentionRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java new file mode 100644 index 0000000000..6f1cba49c5 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class RuntimeInstanceCleanupServiceImplTest { + private static final Long TENANT_ID = 29L; + private static final String GAME_INSTANCE_ID = "runtime-opaque"; + private static final String TERMINATION_REQUEST_ID = "termination-request"; + + @Test + void observedEmptyTargetReturnsZeroCountsWithoutDeletingAnyFamily() { + Dependencies dependencies = new Dependencies(); + when(dependencies.retentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(false); + + var result = + dependencies + .service() + .cleanupRuntimeInstance(TENANT_ID, GAME_INSTANCE_ID, TERMINATION_REQUEST_ID); + + assertThat(result.deletedRoomGroundEntries()).isZero(); + assertThat(result.deletedItemStacks()).isZero(); + assertThat(result.deletedItemInstances()).isZero(); + assertThat(result.deletedContainerInstances()).isZero(); + } + + @Test + void unclassifiedOrQuarantinedEvidenceDeniesCleanupWithoutMutation() { + Dependencies dependencies = new Dependencies(); + when(dependencies.retentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(true); + + assertThatThrownBy( + () -> + dependencies + .service() + .cleanupRuntimeInstance(TENANT_ID, GAME_INSTANCE_ID, TERMINATION_REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); + } + + private static final class Dependencies { + private final QuarantinedActorRetentionRepository retentionRepository = + Mockito.mock(QuarantinedActorRetentionRepository.class); + + private RuntimeInstanceCleanupServiceImpl service() { + return new RuntimeInstanceCleanupServiceImpl(retentionRepository); + } + } +} From 631e15924dd53c353d37fde815af8152e6caf587 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 13:01:46 +1300 Subject: [PATCH 03/39] fix(entity-management): use session locks for concurrent index migrations --- .../runtime-and-data.md | 1 + .../gameplay-rules-entities-and-effects.md | 2 +- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + .../RetainedActorIdentityIntegrationTest.java | 21 ++++++-- ...FlywayPostgresqlLockConfigurationTest.java | 53 +++++++++++++++++++ .../src/test/resources/application.yml | 4 ++ 7 files changed, 79 insertions(+), 6 deletions(-) create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index a60d825067..8f3dfac137 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,6 +13,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. +- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. A prior Entity integrationTest run stalled for 17 minutes and was cancelled at the 20-minute job limit; the transactional-lock interaction is the inferred cause. A successful PostgreSQL migration run after this configuration change has not yet been observed. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 4cea2611e5..6854ffcad6 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,7 +26,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `partial` - The full Entity unit task passed 203 tests with zero failures/errors/skips, including persisted-row update guards and observation-only cleanup. Five `RetainedActorIdentityIntegrationTest` PostgreSQL cases compiled but are unexecuted on the corrected V2–V4 chain because local Docker is disabled. The migration/SQL-isolation assertions are authored, not executed; fixture-created `OWNER_RESOLVED` rows test SQL predicates only, not owner-backed runtime provenance. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `partial` - The full Entity unit task passed 203 tests with zero failures/errors/skips, including persisted-row update guards and observation-only cleanup. Five `RetainedActorIdentityIntegrationTest` PostgreSQL cases compiled but are unexecuted on the corrected V2–V4 chain because local Docker is disabled. The migration/SQL-isolation assertions are authored, not executed; fixture-created `OWNER_RESOLVED` rows test SQL predicates only, not owner-backed runtime provenance. The new Flyway configuration unit test covers Spring property binding and Flyway's PostgreSQL configuration API. A prior Entity CI integrationTest run stalled for 17 minutes and was cancelled at the 20-minute job limit; the advisory-lock explanation remains inferred, with no post-change live PostgreSQL proof yet. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `partial` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `partial` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `partial` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | diff --git a/services/entity-management-service/src/main/resources/application-prod.yml b/services/entity-management-service/src/main/resources/application-prod.yml index fd6533c6f2..5bd8518afb 100644 --- a/services/entity-management-service/src/main/resources/application-prod.yml +++ b/services/entity-management-service/src/main/resources/application-prod.yml @@ -4,6 +4,8 @@ spring: name: entity-management-service flyway: enabled: true + postgresql: + transactional-lock: false schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index d3b5e99641..54a96253b4 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -3,6 +3,8 @@ spring: name: entity-management-service flyway: enabled: true + postgresql: + transactional-lock: false schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 0b9b2a1e93..2ef91486fb 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -7,7 +7,9 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.time.Instant; +import java.util.Map; import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; import net.firedevops.firemud.entitymanagement.entity.Character; @@ -24,8 +26,10 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -601,6 +605,7 @@ void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { } @Test + @Timeout(value = 3, unit = TimeUnit.MINUTES) void flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLException { migrateLegacySchemaToV1(); try (Connection connection = connectToMigrationSchema()) { @@ -916,11 +921,17 @@ private void migrateLegacySchemaToLatest() { } private FluentConfiguration migrationFlyway() { - return Flyway.configure() - .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) - .schemas(migrationSchema) - .defaultSchema(migrationSchema) - .locations("classpath:db/migration"); + FluentConfiguration configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(migrationSchema) + .defaultSchema(migrationSchema) + .locations("classpath:db/migration"); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration.jdbcProperties( + Map.of("options", "-c lock_timeout=30s -c statement_timeout=120s")); } private Connection connectToMigrationSchema() throws SQLException { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java new file mode 100644 index 0000000000..d852782d19 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.flyway.autoconfigure.FlywayProperties; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; + +class FlywayPostgresqlLockConfigurationTest { + @Test + void allServiceProfilesBindSessionLevelPostgresqlAdvisoryLocks() throws IOException { + for (Path resourcePath : + List.of( + Path.of("src/main/resources/application.yml"), + Path.of("src/main/resources/application-prod.yml"), + Path.of("src/test/resources/application.yml"))) { + var propertySource = + new YamlPropertySourceLoader() + .load(resourcePath.toString(), new FileSystemResource(resourcePath.toFile())) + .getFirst(); + var environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(propertySource); + + FlywayProperties properties = + Binder.get(environment) + .bind("spring.flyway", FlywayProperties.class) + .orElseThrow( + () -> new AssertionError("Flyway settings did not bind from " + resourcePath)); + + assertThat(properties.getPostgresql().getTransactionalLock()) + .as("PostgreSQL transactional advisory locks in %s", resourcePath) + .isFalse(); + } + } + + @Test + void manualFlywayConfigurationUsesSessionLevelPostgresqlAdvisoryLocks() { + var configuration = Flyway.configure(); + var postgresql = + configuration.getConfigurationExtension(PostgreSQLConfigurationExtension.class); + postgresql.setTransactionalLock(false); + + assertThat(postgresql.isTransactionalLock()).isFalse(); + } +} diff --git a/services/entity-management-service/src/test/resources/application.yml b/services/entity-management-service/src/test/resources/application.yml index ec1671a55b..cd57d6839c 100644 --- a/services/entity-management-service/src/test/resources/application.yml +++ b/services/entity-management-service/src/test/resources/application.yml @@ -1,3 +1,7 @@ FIREMUD_GRPC_CERT_CHAIN_PATH: classpath:certs/dev-cert.pem FIREMUD_GRPC_PRIVATE_KEY_PATH: classpath:certs/dev-key.pem FIREMUD_GRPC_CA_CERT_PATH: classpath:certs/dev-ca.pem +spring: + flyway: + postgresql: + transactional-lock: false From 400dfe0a75d5e7ba5f17043d7fed3d6bcc6333ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 13:34:20 +1300 Subject: [PATCH 04/39] fix(entity): complete migration fixture and review corrections --- .../entity-management-service/operations.md | 59 +++++++++++++++++++ .../gameplay-rules-entities-and-effects.md | 2 +- .../repository/ActorIdentityRepository.java | 4 -- .../RetainedActorIdentityIntegrationTest.java | 3 +- 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 0be0214be6..8398933cbe 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -10,6 +10,65 @@ The current replacement-validation path is also narrower than the target contrac At the live enqueue boundary, the current Automation implementation expands each enabled command node over its target entity ids, assigns `commandOrdinal`, and enforces configured bounded per-run and per-entity fan-out with atomic rejection before admission when a bound is exceeded. The current path still does not prove complete durable child/target identity or end-to-end fan-out/replay semantics; the target Command-Handoff Identity and its atomic rejection distinction remain required. `automationDispatchId` alone is not a dedupe key; use the complete Command-Handoff Identity for the target contract. +## V3 Concurrent Index Migration Recovery + +Entity V3 creates `ux_characters_character_uuid_idx` concurrently, then `idx_characters_owner_resolved_roster` concurrently, and finally attaches the first index as the `ux_characters_character_uuid` unique constraint. Follow the [database migration contract](../../system-architecture-database-migrations.md) for migration activation and roll-forward. These local recovery steps preserve all character rows and require writer admission to remain closed and quiesced throughout inspection and recovery. + +Use the deployed Entity `SERVICE_SCHEMA` value, confirm the selected schema, and inspect the exact index definitions, PostgreSQL validity/readiness flags, and any attached constraint before taking action. In `psql`, set `service_schema` to that deployed schema and run: + +```sql +SET search_path TO :"service_schema"; + +SELECT current_schema() AS selected_schema, current_schemas(false) AS search_path_schemas; + +SELECT ns.nspname AS schema_name, + idx.relname AS index_name, + pg_get_indexdef(idx.oid) AS index_definition, + pi.indisvalid, + pi.indisready, + pi.indisunique, + con.conname AS attached_constraint +FROM pg_class AS idx +JOIN pg_namespace AS ns ON ns.oid = idx.relnamespace +JOIN pg_index AS pi ON pi.indexrelid = idx.oid +LEFT JOIN pg_constraint AS con ON con.conindid = idx.oid +WHERE ns.nspname = :'service_schema' + AND idx.relname IN ( + 'ux_characters_character_uuid_idx', + 'idx_characters_owner_resolved_roster', + 'ux_characters_character_uuid' + ) +ORDER BY idx.relname; +``` + +Before a concurrent index build or drop, inspect long-running transactions and blockers in the target database; concurrent index operations can wait on old snapshots and other transactions. This read-only query identifies long-running active transactions and sessions blocking or blocked by another backend: + +```sql +SELECT activity.pid, + activity.usename, + activity.state, + now() - activity.xact_start AS transaction_age, + now() - activity.query_start AS query_age, + activity.wait_event_type, + activity.wait_event, + pg_blocking_pids(activity.pid) AS blocking_pids, + activity.query +FROM pg_stat_activity AS activity +WHERE activity.datname = current_database() + AND activity.pid <> pg_backend_pid() + AND (activity.state <> 'idle' OR cardinality(pg_blocking_pids(activity.pid)) > 0) +ORDER BY activity.xact_start NULLS LAST, activity.query_start NULLS LAST; +``` + +An invalid index may be removed only after confirming it is one of these exact V3 indexes, is unattached to a constraint, and its definition matches the expected V3 object. Use the deployed schema explicitly; run each statement outside a transaction: + +```sql +DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".ux_characters_character_uuid_idx; +DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".idx_characters_owner_resolved_roster; +``` + +Drop only the specific invalid, unattached index confirmed by inspection, then verify it is absent. Do not drop a valid index or the attached `ux_characters_character_uuid` constraint as generic cleanup. A blind Flyway repair-and-migrate is unsafe when an earlier V3 statement succeeded: retrying the whole file may collide with a surviving valid index, and attaching the unique index renames it to the constraint's final name. If either expected index is valid, the final constraint exists, or the observed state is otherwise mixed, stop automatic retry and use an operator-reviewed, phase-specific roll-forward plan that accounts for Flyway history and the exact surviving definitions. Do not delete or rewrite character data to make the migration proceed. + ## Target Replacement Operations Replacement operations use the stable `playableStateNamespaceId` and owner-resolved `playableStateScope` for durable S1/S2 state and the active `gameInstanceId` as a runtime fence; Entity validates the scope and never derives it from the opaque namespace. Explicitly disposable S3 families may remain instance-keyed. Entity must report owner-local classification, mapping validation/application, and cleanup acknowledgement to World Management. Unknown or unregistered families block cutover/termination, and an echoed `remapSetId` is not proof of mapping application. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) own the cross-service decisions; this file records the Entity operational consequence. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 6854ffcad6..47c9391217 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -31,7 +31,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `partial` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `partial` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | | GR-4.2 Combat and conflict resolution | `not-implemented` - no combat/conflict resolver or authoritative combat loop is present. | `audited` - adjacent action-state/effect tests were inspected, but no focused combat proof exists. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md) | No production anchor: no combat owner is implemented. Adjacent context only: [ActionStateCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) and [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java) are non-combat seams. | No focused executable proof. [ActionStateCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java) is legacy context for the removed transient action-state handler path, not current combat proof; this does not mean the live durable `BLOCK` gameplay command or its replay-record category was removed. | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [GR-1.2](./game-session-runtime-and-tick-coordination.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Damage packets, hit/mitigation ordering, combat timing, body-region resolution, and combat-driven defeat/loot/revival/victory behavior remain absent. | -| GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads are live; ability and skill progression is not. | `proven` - focused character progression and actor-state tests cover the bounded XP/level seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | +| GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads exist, but production XP/level mutation remains fail-closed pending owner-qualified actor resolution; ability and skill progression is not implemented. | `partial` - focused character progression and actor-state tests prove bounded service behavior with a mocked resolver; this conditional proof does not establish production owner-qualified admission. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | | GR-4.4 In-game economy, trading, crafting, and exchange | `partial` - version-scoped recipe/ingredient persistence and CRUD APIs exist; gameplay crafting, economy, trading, and exchange do not. | `proven` - focused crafting controller/service tests cover recipe persistence and validation; item transfer tests cover only the adjacent substrate. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Entity API current status](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status) | [CraftingServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImpl.java); [CraftingController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java); [CraftingRecipe.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CraftingRecipe.java); [crafting schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [CraftingServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImplTest.java); [CraftingControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Material consumption/result creation, currency and vendor policy, trade/exchange flows, and end-to-end player proof remain absent. | ## Canonical Design Sources diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java index 1d2eca7ecb..83de1b6c5c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java @@ -37,10 +37,6 @@ public List findOwnerResolvedRoster( UUID namespace = ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); - if (scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - && scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) { - throw new IllegalArgumentException("playableStateScope is not a supported resolved scope"); - } return dsl.select( CHARACTERS.CHARACTER_UUID, CHARACTERS.ACCOUNT_UUID, diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 2ef91486fb..48a065a397 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -926,7 +926,8 @@ private FluentConfiguration migrationFlyway() { .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) .schemas(migrationSchema) .defaultSchema(migrationSchema) - .locations("classpath:db/migration"); + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", migrationSchema)); configuration .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); From 67b4934b736f700ef913d9cd166dc78713f88a58 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 14:16:47 +1300 Subject: [PATCH 05/39] fix(entity): align proof states and reject self-friendship precisely --- .../gameplay-rules-entities-and-effects.md | 10 +- .../repository/CharacterFriendRepository.java | 4 + .../RetainedActorIdentityIntegrationTest.java | 34 +++-- .../CharacterFriendRepositoryTest.java | 133 ++++++++++++++++++ 4 files changed, 161 insertions(+), 20 deletions(-) create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 47c9391217..6829123c02 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,12 +26,12 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `partial` - The full Entity unit task passed 203 tests with zero failures/errors/skips, including persisted-row update guards and observation-only cleanup. Five `RetainedActorIdentityIntegrationTest` PostgreSQL cases compiled but are unexecuted on the corrected V2–V4 chain because local Docker is disabled. The migration/SQL-isolation assertions are authored, not executed; fixture-created `OWNER_RESOLVED` rows test SQL predicates only, not owner-backed runtime provenance. The new Flyway configuration unit test covers Spring property binding and Flyway's PostgreSQL configuration API. A prior Entity CI integrationTest run stalled for 17 minutes and was cancelled at the 20-minute job limit; the advisory-lock explanation remains inferred, with no post-change live PostgreSQL proof yet. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | -| GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `partial` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | -| GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `partial` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | -| GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `partial` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `audited` - CI run 37165391640 executed all nine Entity integration tests against PostgreSQL 16.15 with zero failures or skips, including all five retained-actor cases. This is executed bounded migration, SQL-isolation, and runtime-quarantine proof; fixture-created `OWNER_RESOLVED` rows exercise SQL predicates only and do not establish owner-backed runtime provenance. The corrected Entity unit suite passed 208 tests in 40 suites with zero failures, errors, or skips; trusted owner-backed runtime provenance and PLAY remain unproved. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | +| GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `audited` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | +| GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | +| GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `audited` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | | GR-4.2 Combat and conflict resolution | `not-implemented` - no combat/conflict resolver or authoritative combat loop is present. | `audited` - adjacent action-state/effect tests were inspected, but no focused combat proof exists. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md) | No production anchor: no combat owner is implemented. Adjacent context only: [ActionStateCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) and [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java) are non-combat seams. | No focused executable proof. [ActionStateCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java) is legacy context for the removed transient action-state handler path, not current combat proof; this does not mean the live durable `BLOCK` gameplay command or its replay-record category was removed. | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [GR-1.2](./game-session-runtime-and-tick-coordination.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Damage packets, hit/mitigation ordering, combat timing, body-region resolution, and combat-driven defeat/loot/revival/victory behavior remain absent. | -| GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads exist, but production XP/level mutation remains fail-closed pending owner-qualified actor resolution; ability and skill progression is not implemented. | `partial` - focused character progression and actor-state tests prove bounded service behavior with a mocked resolver; this conditional proof does not establish production owner-qualified admission. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | +| GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads exist, but production XP/level mutation remains fail-closed pending owner-qualified actor resolution; ability and skill progression is not implemented. | `audited` - focused character progression and actor-state tests prove bounded service behavior with a mocked resolver; this conditional proof does not establish production owner-qualified admission. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | | GR-4.4 In-game economy, trading, crafting, and exchange | `partial` - version-scoped recipe/ingredient persistence and CRUD APIs exist; gameplay crafting, economy, trading, and exchange do not. | `proven` - focused crafting controller/service tests cover recipe persistence and validation; item transfer tests cover only the adjacent substrate. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Entity API current status](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status) | [CraftingServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImpl.java); [CraftingController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java); [CraftingRecipe.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CraftingRecipe.java); [crafting schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [CraftingServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImplTest.java); [CraftingControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Material consumption/result creation, currency and vendor policy, trade/exchange flows, and end-to-end player proof remain absent. | ## Canonical Design Sources diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java index af5a062bac..ef9c9da515 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java @@ -5,6 +5,7 @@ import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTER_FRIEND; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; @@ -56,6 +57,9 @@ public Optional findById(CharacterFriendKey key) { } public CharacterFriend save(CharacterFriend entity) { + if (Objects.equals(entity.getId().getCharacterId(), entity.getId().getFriendId())) { + throw new IllegalStateException("FRIEND_SELF_RELATIONSHIP_NOT_ALLOWED"); + } long ownerResolvedCount = dsl.fetchCount( CHARACTERS, diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 48a065a397..cceca1e57d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -8,6 +8,7 @@ import java.sql.SQLException; import java.time.Instant; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; @@ -867,21 +868,24 @@ private long insertActor( String quarantineReason, long legacyAccountId, long legacyTenantId) { - return jdbcTemplate.queryForObject( - "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", - Long.class, - legacyAccountId, - name, - legacyTenantId, - legacyStateKey, - characterUuid, - accountUuid, - tenantUuid, - namespaceUuid, - scope == null ? null : scope.name(), - status, - quarantineReason); + Long actorId = + jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + Long.class, + legacyAccountId, + name, + legacyTenantId, + legacyStateKey, + characterUuid, + accountUuid, + tenantUuid, + namespaceUuid, + scope == null ? null : scope.name(), + status, + quarantineReason); + return Objects.requireNonNull( + actorId, "Character INSERT ... RETURNING id must return the inserted actor ID"); } private void insertItemInstance( diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java new file mode 100644 index 0000000000..e0608c913d --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTER_FRIEND; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record1; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class CharacterFriendRepositoryTest { + private static final Long TENANT_ID = 17L; + private static final Long CHARACTER_ID = 37L; + private static final Long FRIEND_ID = 41L; + + @Test + void saveRejectsSelfRelationshipBeforeDatabaseInteraction() { + AtomicInteger queryCount = new AtomicInteger(); + CharacterFriendRepository repository = + repository( + context -> { + queryCount.incrementAndGet(); + throw new AssertionError( + "self relationships must be rejected before database access"); + }); + + assertThatThrownBy(() -> repository.save(friend(CHARACTER_ID, CHARACTER_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FRIEND_SELF_RELATIONSHIP_NOT_ALLOWED"); + assertThat(queryCount).hasValue(0); + } + + @Test + void saveStillRejectsDistinctPairWithoutTwoOwnerResolvedActors() { + AtomicInteger queryCount = new AtomicInteger(); + AtomicReference guardBindings = new AtomicReference<>(); + CharacterFriendRepository repository = + repository( + context -> { + queryCount.incrementAndGet(); + guardBindings.set(context.bindings()); + return ownerResolvedCountResult(1); + }); + + assertThatThrownBy(() -> repository.save(friend(CHARACTER_ID, FRIEND_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FRIEND_ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + assertThat(queryCount).hasValue(1); + assertThat(Arrays.asList(guardBindings.get())) + .contains(CHARACTER_ID, FRIEND_ID, TENANT_ID, "OWNER_RESOLVED"); + } + + @Test + void saveChecksExactTenantAndOwnerResolvedGuardForDistinctPair() { + AtomicInteger queryCount = new AtomicInteger(); + AtomicReference guardSql = new AtomicReference<>(); + AtomicReference guardBindings = new AtomicReference<>(); + CharacterFriend entity = friend(CHARACTER_ID, FRIEND_ID); + CharacterFriendRepository repository = + repository( + context -> { + queryCount.incrementAndGet(); + String sql = context.sql().trim(); + if (sql.toLowerCase(Locale.ROOT).startsWith("select count")) { + guardSql.set(sql); + guardBindings.set(context.bindings()); + return ownerResolvedCountResult(2); + } + if (sql.toLowerCase(Locale.ROOT).startsWith("select")) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(CHARACTER_FRIEND.fields())) + }; + } + if (sql.toLowerCase(Locale.ROOT).startsWith("insert")) { + return new MockResult[] {new MockResult(1)}; + } + throw new AssertionError("Unexpected database interaction: " + sql); + }); + + assertThat(repository.save(entity)).isSameAs(entity); + + String normalizedGuardSql = guardSql.get().toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); + assertThat(normalizedGuardSql) + .contains(" from \"characters\"") + .contains("\"id\" in (?, ?)") + .contains("\"tenant_id\" = ?") + .contains("\"actor_identity_status\" = ?"); + assertThat(Arrays.asList(guardBindings.get())) + .contains(CHARACTER_ID, FRIEND_ID, TENANT_ID, "OWNER_RESOLVED"); + assertThat(queryCount).hasValue(3); + } + + private static CharacterFriendRepository repository(MockDataProvider provider) { + return new CharacterFriendRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + } + + private static MockResult[] ownerResolvedCountResult(int count) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + Field countField = DSL.field("count", Integer.class); + Record1 countRow = resultDsl.newRecord(countField); + countRow.set(countField, count); + Result> countResult = resultDsl.newResult(countField); + countResult.add(countRow); + return new MockResult[] {new MockResult(1, countResult)}; + } + + private static CharacterFriend friend(Long characterId, Long friendId) { + CharacterFriendKey key = new CharacterFriendKey(); + key.setCharacterId(characterId); + key.setFriendId(friendId); + CharacterFriend entity = new CharacterFriend(); + entity.setId(key); + entity.setTenantId(TENANT_ID); + entity.setCreatedAt(Instant.parse("2024-01-03T00:00:00Z")); + return entity; + } +} From 3ace5c478826aec68bafdd934ce7fe8381dd7588 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:44:19 +1300 Subject: [PATCH 06/39] Fence character updates by tenant and refresh migration proof --- .../runtime-and-data.md | 2 +- .../repository/CharacterRepository.java | 2 +- .../RetainedActorIdentityIntegrationTest.java | 44 +++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 8f3dfac137..92bb629506 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,7 +13,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. -- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. A prior Entity integrationTest run stalled for 17 minutes and was cancelled at the 20-minute job limit; the transactional-lock interaction is the inferred cause. A successful PostgreSQL migration run after this configuration change has not yet been observed. +- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. PostgreSQL 16.15 CI run `37165391640` executed all nine Entity integration cases, including the V1-to-latest migration and retained-actor cases, with zero failures or skips after this configuration change. Develop-based full-stack Smoke proof remains outstanding. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 68ea9493f0..8a219fcebf 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -188,13 +188,13 @@ public Character save(Character entity) { .set(CHARACTERS.STAMINA, entity.getStamina()) .set(CHARACTERS.HEALTH, entity.getHealth()) .set(CHARACTERS.MANA, entity.getMana()) - .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) .set(CHARACTERS.LAST_LOGIN_AT, toLocalDateTime(entity.getLastLoginAt())) .set(CHARACTERS.VERSION, entity.getVersion() + 1) .where( CHARACTERS .ID .eq(entity.getId()) + .and(CHARACTERS.TENANT_ID.eq(entity.getTenantId())) .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) .execute(); if (updatedRows != 1) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index cceca1e57d..d481d44037 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -856,6 +856,50 @@ private void assertNamespaceIdentityUpdateRejected(String sql, Object... argumen .hasMessageContaining("entity playable-state namespace identity is immutable"); } + @Test + void characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch() { + UUID characterUuid = UUID.fromString("40000000-0000-4000-8000-000000000010"); + long actorId = + insertActor( + "Tenant-owned actor", + characterUuid, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + ACCOUNT_ID, + TENANT_ID); + + Character crossTenantUpdate = + characterRepository.findByIdAndTenantId(actorId, TENANT_ID).orElseThrow(); + int originalVersion = crossTenantUpdate.getVersion(); + int originalExperience = crossTenantUpdate.getExperience(); + crossTenantUpdate.setTenantId(TENANT_ID + 1); + crossTenantUpdate.setName("Cross-tenant overwrite"); + crossTenantUpdate.setExperience(originalExperience + 99); + + assertThatThrownBy(() -> characterRepository.save(crossTenantUpdate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CHARACTER_IDENTITY_NOT_OWNER_RESOLVED"); + + Character unchanged = characterRepository.findByIdAndTenantId(actorId, TENANT_ID).orElseThrow(); + assertThat(unchanged.getTenantId()).isEqualTo(TENANT_ID); + assertThat(unchanged.getName()).isEqualTo("Tenant-owned actor"); + assertThat(unchanged.getExperience()).isEqualTo(originalExperience); + assertThat(unchanged.getVersion()).isEqualTo(originalVersion); + + Character validUpdate = + characterRepository.findByIdAndTenantId(actorId, TENANT_ID).orElseThrow(); + validUpdate.setName("Tenant-owned actor updated"); + Character saved = characterRepository.save(validUpdate); + assertThat(saved.getTenantId()).isEqualTo(TENANT_ID); + assertThat(saved.getName()).isEqualTo("Tenant-owned actor updated"); + assertThat(saved.getVersion()).isEqualTo(originalVersion + 1); + } + private long insertActor( String name, UUID characterUuid, From d6ec652954fe3edc225fc88327d41a57836aa89a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:46:37 +1300 Subject: [PATCH 07/39] Align character update limitation with tenant fence --- .../microservices/entity-management-service/runtime-and-data.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 92bb629506..7da98729c1 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -11,7 +11,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The `entitymanagement.mutation.effect.execution{operation,effect_status}` metric distinguishes first apply, replay/no-op, in-progress conflict, reported reuse outcome, and unreadable stored-response outcomes. - This current `{tenantId,effectId}` identity is not the target ADR 0054 participant guard: the replay record persists only the operation/status/payload result and reuse checks only the operation name. It does not yet persist or validate the typed target, namespace/scope/fence, or immutable request digest, and changed operation, target, or request reuse is not yet proven fail-closed. - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. -- Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. +- Character updates are not currently optimistic CAS: `CharacterRepository` increments `version` and requires an exact tenant/row ID match, `OWNER_RESOLVED` status, and one affected row, but does not compare the old version or bind the update to namespace identity. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. - Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. PostgreSQL 16.15 CI run `37165391640` executed all nine Entity integration cases, including the V1-to-latest migration and retained-actor cases, with zero failures or skips after this configuration change. Develop-based full-stack Smoke proof remains outstanding. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. From 466830d12614f50f5291318714727c13504cec0a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:58:09 +1300 Subject: [PATCH 08/39] Initialize tenant-fence proof namespace and distinguish historical coverage --- .../microservices/entity-management-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- .../entitymanagement/RetainedActorIdentityIntegrationTest.java | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 7da98729c1..56fe66efff 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,7 +13,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are not currently optimistic CAS: `CharacterRepository` increments `version` and requires an exact tenant/row ID match, `OWNER_RESOLVED` status, and one affected row, but does not compare the old version or bind the update to namespace identity. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. -- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. PostgreSQL 16.15 CI run `37165391640` executed all nine Entity integration cases, including the V1-to-latest migration and retained-actor cases, with zero failures or skips after this configuration change. Develop-based full-stack Smoke proof remains outstanding. +- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. Prior-head PostgreSQL 16.15 CI run `37165391640` executed all nine Entity integration cases then present, including the V1-to-latest migration and five retained-actor cases, with zero failures or skips after this configuration change. The current integration suite has ten cases, including six retained-actor cases; execution of the new wrong-tenant update regression remains pending and is not covered by the historical run. Develop-based full-stack Smoke proof remains outstanding. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 6829123c02..54c1a70589 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,7 +26,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `audited` - CI run 37165391640 executed all nine Entity integration tests against PostgreSQL 16.15 with zero failures or skips, including all five retained-actor cases. This is executed bounded migration, SQL-isolation, and runtime-quarantine proof; fixture-created `OWNER_RESOLVED` rows exercise SQL predicates only and do not establish owner-backed runtime provenance. The corrected Entity unit suite passed 208 tests in 40 suites with zero failures, errors, or skips; trusted owner-backed runtime provenance and PLAY remain unproved. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `audited` - Prior-head CI run 37165391640 executed all nine Entity integration tests against PostgreSQL 16.15 with zero failures or skips, including the five retained-actor cases then present. The current retained-actor class has six cases; execution of the new wrong-tenant character-update case and current ten-test integration suite remains pending, not proved by that historical run. This is executed bounded migration, SQL-isolation, and runtime-quarantine proof; fixture-created `OWNER_RESOLVED` rows exercise SQL predicates only and do not establish owner-backed runtime provenance. The corrected Entity unit suite passed 208 tests in 40 suites with zero failures, errors, or skips; trusted owner-backed runtime provenance and PLAY remain unproved. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `audited` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `audited` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index d481d44037..6a8f20f9c5 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -859,6 +859,7 @@ private void assertNamespaceIdentityUpdateRejected(String sql, Object... argumen @Test void characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch() { UUID characterUuid = UUID.fromString("40000000-0000-4000-8000-000000000010"); + insertNamespace(TENANT_UUID, NAMESPACE_UUID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); long actorId = insertActor( "Tenant-owned actor", From a4fe745c363cb8d94f649f1ad408665d1ee7b1be Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:37:32 +1300 Subject: [PATCH 09/39] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aab6706691..8970557348 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1022,7 +1022,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index ccbb89354c..985a365ce1 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -355,6 +355,44 @@ if "workflow_dispatch" not in events: raise SystemExit("Validation must retain manual dispatch") PYTHON +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1524,6 +1562,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1994,6 +2041,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2026,13 +2074,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2046,8 +2097,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2058,6 +2125,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { From d9f710631df4816c5a6bd80b93df469001502bf2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:26:18 +1300 Subject: [PATCH 10/39] test(entity): isolate quarantined audit retention outcomes --- .../runtime-and-data.md | 2 +- .../RetainedActorIdentityIntegrationTest.java | 138 ++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 56fe66efff..85183617b4 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,7 +13,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are not currently optimistic CAS: `CharacterRepository` increments `version` and requires an exact tenant/row ID match, `OWNER_RESOLVED` status, and one affected row, but does not compare the old version or bind the update to namespace identity. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. -- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. Prior-head PostgreSQL 16.15 CI run `37165391640` executed all nine Entity integration cases then present, including the V1-to-latest migration and five retained-actor cases, with zero failures or skips after this configuration change. The current integration suite has ten cases, including six retained-actor cases; execution of the new wrong-tenant update regression remains pending and is not covered by the historical run. Develop-based full-stack Smoke proof remains outstanding. +- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. See [GR-3.1 implementation and proof status](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for the current integration evidence and remaining gaps. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 6a8f20f9c5..a80498c5e3 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -563,6 +563,144 @@ void quarantinedActorLookupMutationExpiryAndCleanupRemainHeld() { .isEqualTo("aabb"); } + @Test + void destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows() { + String auditOnlyInstance = "GI-RETAINED-AUDIT-ONLY"; + long quarantinedActorId = + insertActor( + "legacy audit destination", + UUID.fromString("42000000-0000-4000-8000-000000000001"), + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + ACCOUNT_ID, + TENANT_ID); + jdbcTemplate.update( + "INSERT INTO item_transfer_audits " + + "(id, tenant_id, item_id, quantity, verb, effect_id, correlation_key, source_holder_kind, source_game_instance_id, destination_holder_kind, destination_character_id, destination_game_instance_id) " + + "VALUES (3601, ?, 3001, 1, 'TAKE', 'effect-audit-only-quarantined', 'corr-audit-only-quarantined', 'ROOM', ?, 'CHARACTER', ?, ?)", + TENANT_ID, + auditOnlyInstance, + quarantinedActorId, + auditOnlyInstance); + + assertNoRuntimeRowsForInstance(auditOnlyInstance); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE id = 3601 AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", + Integer.class, + quarantinedActorId)) + .isEqualTo(1); + assertThat( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + TENANT_ID, auditOnlyInstance)) + .isTrue(); + assertThatThrownBy( + () -> + runtimeInstanceCleanupService.cleanupRuntimeInstance( + TENANT_ID, auditOnlyInstance, "termination-audit-only-quarantined")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE id = 3601 AND tenant_id = ? AND correlation_key = 'corr-audit-only-quarantined' AND destination_character_id = ?", + Integer.class, + TENANT_ID, + quarantinedActorId)) + .isEqualTo(1); + assertNoRuntimeRowsForInstance(auditOnlyInstance); + } + + @Test + void destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows() { + String auditOnlyInstance = "GI-RETAINED-AUDIT-OWNER-RESOLVED"; + long ownerResolvedActorId = + insertActor( + "owner-resolved audit destination fixture", + UUID.fromString("43000000-0000-4000-8000-000000000001"), + UUID.fromString("43000000-0000-4000-8000-000000000002"), + UUID.fromString("43000000-0000-4000-8000-000000000003"), + UUID.fromString("43000000-0000-4000-8000-000000000004"), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + ACCOUNT_ID, + TENANT_ID); + jdbcTemplate.update( + "INSERT INTO item_transfer_audits " + + "(id, tenant_id, item_id, quantity, verb, effect_id, correlation_key, source_holder_kind, source_game_instance_id, destination_holder_kind, destination_character_id, destination_game_instance_id) " + + "VALUES (3602, ?, 3001, 1, 'TAKE', 'effect-audit-only-owner-resolved', 'corr-audit-only-owner-resolved', 'ROOM', ?, 'CHARACTER', ?, ?)", + TENANT_ID, + auditOnlyInstance, + ownerResolvedActorId, + auditOnlyInstance); + + assertNoRuntimeRowsForInstance(auditOnlyInstance); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE id = 3602 AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", + Integer.class, + ownerResolvedActorId)) + .isEqualTo(1); + assertThat( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + TENANT_ID, auditOnlyInstance)) + .isFalse(); + var result = + runtimeInstanceCleanupService.cleanupRuntimeInstance( + TENANT_ID, auditOnlyInstance, "termination-audit-only-owner-resolved"); + assertThat(result).isNotNull(); + assertThat(result.deletedItemInstances()).isZero(); + assertThat(result.deletedContainerInstances()).isZero(); + assertThat(result.deletedItemStacks()).isZero(); + assertThat(result.deletedRoomGroundEntries()).isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE id = 3602 AND tenant_id = ? AND correlation_key = 'corr-audit-only-owner-resolved' AND destination_character_id = ?", + Integer.class, + TENANT_ID, + ownerResolvedActorId)) + .isEqualTo(1); + assertNoRuntimeRowsForInstance(auditOnlyInstance); + } + + private void assertNoRuntimeRowsForInstance(String gameInstanceId) { + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_instances WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + gameInstanceId)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + gameInstanceId)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + gameInstanceId)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + TENANT_ID, + gameInstanceId)) + .isZero(); + } + @Test void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { insertActor( From 33653433480ff9195852365a6dd010f21f0c9d45 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:53:55 +1300 Subject: [PATCH 11/39] Fix Entity audit fixture namespace and proof status --- .../entity-management-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- .../RetainedActorIdentityIntegrationTest.java | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 85183617b4..97dca3e2f3 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -306,7 +306,7 @@ See [Versioning & Runtime Configuration](../../system-architecture-versioning-ru - The first shared effect-evaluation seam is an in-process Entity Management service that evaluates typed resource modifiers and granted states deterministically. Active condition payloads and equipped item-template payloads are `CONTINUOUS` effect sources: they contribute while their source exists and never write derived values into current resources during reads. When an attached source changes a bounded-resource maximum, its attach, detach, refresh, expiry, or replacement mutation performs the one idempotent capacity normalization using the declaration override or resolved tenant/game `actorState.capacityChangePolicy` captured by that mutation. Evaluation reads never normalize current state. Gameplay-attested `ApplyActorCondition` calls are the first `INSTANT` mutation path, creating active condition/action-state rows through the same internal mutation service under an idempotent effect id. A scheduled Entity Management job globally and without a batch bound deletes elapsed active-condition rows on a 30-second default fixed delay measured after the previous invocation completes; read-time filtering prevents expired effects from being restored before cleanup. The job does not delete separate `entity_mutation_effects` receipts, which are checked before mutation, but receipt-retention and typed replay/concurrency proof remain target gaps. Player command wiring remains future work. - Target-state active-condition rows are condition instances with stable instance ids, frozen definition/release snapshots, source provenance, stack counts, expiry, and applied-effect snapshots. Condition-definition DML, not source-id coincidence, selects `REPLACE`, `REFRESH`, `STACK`, or `PARALLEL` reapplication behavior and its duration policy. Typed removal resolves exact keys, authored tags, or permitted sources in deterministic definition priority and instance-id order; it must not expose raw row or payload deletion to player-facing callers. - Target only: World Management will own character/NPC location and instance-membership rows and their authoritative reads/writes; those tables and paths are not present in the current implementation. Entity Management owns and persists item instances and inventories, but must not add competing actor-location fields or tables. -- Entity graphs cache inventory relationships for fast lookups. +- Target only: Entity graphs will cache namespace-qualified inventory relationships under the [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md) contract. `getWithInventory` currently bypasses the legacy graph cache and reads persisted owner-resolved state, as recorded in [implementation status](#implementation-status). ### Persisted actor and realm-entry identity diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index b76f8bc72f..19b2742022 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,7 +26,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `audited` - Prior-head CI run 37165391640 executed all nine Entity integration tests against PostgreSQL 16.15 with zero failures or skips, including the five retained-actor cases then present. The current retained-actor class has six cases; execution of the new wrong-tenant character-update case and current ten-test integration suite remains pending, not proved by that historical run. This is executed bounded migration, SQL-isolation, and runtime-quarantine proof; fixture-created `OWNER_RESOLVED` rows exercise SQL predicates only and do not establish owner-backed runtime provenance. The corrected Entity unit suite passed 208 tests in 40 suites with zero failures, errors, or skips; trusted owner-backed runtime provenance and PLAY remain unproved. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `audited` - Prior-head CI run 37165391640 executed all nine Entity integration tests against PostgreSQL 16.15 with zero failures or skips, including the five retained-actor cases then present. The current retained-actor class has eight cases and the Entity integration tree has twelve; execution of this current suite remains pending, not proved by that historical run. This is executed bounded migration, SQL-isolation, and runtime-quarantine proof; fixture-created `OWNER_RESOLVED` rows exercise SQL predicates only and do not establish owner-backed runtime provenance. The corrected Entity unit suite passed 208 tests in 40 suites with zero failures, errors, or skips; trusted owner-backed runtime provenance and PLAY remain unproved. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `audited` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `audited` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index a80498c5e3..b139d56f98 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -619,6 +619,10 @@ void destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows() { @Test void destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows() { String auditOnlyInstance = "GI-RETAINED-AUDIT-OWNER-RESOLVED"; + insertNamespace( + UUID.fromString("43000000-0000-4000-8000-000000000003"), + UUID.fromString("43000000-0000-4000-8000-000000000004"), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); long ownerResolvedActorId = insertActor( "owner-resolved audit destination fixture", From 757fd8cbc96e9ca69205595b06ab830591454bf0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 01:09:07 +1300 Subject: [PATCH 12/39] Clarify tenant quarantine cutover proof and remove setter-only test --- .../entity-management-service/runtime-and-data.md | 9 ++++++--- .../FlywayPostgresqlLockConfigurationTest.java | 12 ------------ 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 97dca3e2f3..08d96b63dc 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -105,6 +105,7 @@ Implementation notes: - The live implementation enumerates tenant-surviving families (`character`, `inventory`, `character_equipment`, `character_friend`) plus the currently persisted families requiring holder classification (`room_ground_inventory`, `item_instances`, `item_stacks`, `container_instances`). The storage/table family `character` is emitted as the plural wire label `characters` in `checkedFamilies`; that is one explicit storage-to-wire mapping, not two families. The mapping should remain canonicalized or explicitly represented in the target family registry. It does not currently enumerate the durable `actor_resource_states` or `actor_active_conditions` families, even though both are live persistence tables and are consumed by actor-state reads/mutations; the current validation response therefore cannot claim complete actor-state classification. - `item_instances` and `item_stacks` are not table-wide `S3` families: each row follows its holder/container graph. A durable player or durable namespace-backed container holder identified by `(tenantId, playableStateNamespaceId)` plus its domain object identity is `S1` or `S2` according to template-remap requirements; `playableStateScope` remains a separately validated predicate, and only a synthetic room-ground holder or another explicitly instance-scoped holder is `S3`. Termination cleanup must apply the holder/container, namespace, and scope predicates and must not delete all rows in either table by `gameInstanceId` alone. The current table-level enumeration does not yet prove this predicate, so this remains an implementation/proof gap rather than permission to classify durable inventory as `S3`. - `character` and `character_friend` rows have the target `S1` survivor classification within the resolved `(tenantId, playableStateNamespaceId)` identity and immutable scope evidence, and their presence does not require a remap set by itself. At the current boundary this classification is provisional: the live `character`/`character_friend` data is not namespace-isolated proof while legacy `playable_state_key`/namespace-free rows remain, so cutover readers must fail closed or require the completed migration, namespace-aware predicates, and focused isolation proof before treating either family as namespace-backed. +- The live cutover validator counts quarantined characters by tenant through `countQuarantinedByTenantId`, independent of `sourceGameInstanceId`, before evaluating the optional remap. Any such row returns `INCOMPATIBLE` with `ENTITY_ACTOR_IDENTITY_QUARANTINED`, `remapSetRequired=false`, and no approved remap ID; supplying a remap cannot clear the quarantine result. Cutover remains blocked until trusted actor provenance is established. This records current behavior and does not change runtime behavior or expand the target contract. - **Target classification:** `inventory` and `character_equipment` rows are `S2` template-bound survivor state only within the resolved `(tenantId, playableStateNamespaceId)` identity and immutable scope evidence. The current schema has no namespace column for these families, so the live tenant-wide `hasS2Rows` count cannot establish that rows belong to the requested namespace/source instance and is non-authoritative cutover evidence; a namespace-bound implementation must first prove the rows' scope. Under the target contract, if either family has rows in that resolved namespace and no approved `remapSetId` was frozen by launch resolution, validation returns `result=INCOMPATIBLE`, `hasS2Rows=true`, `remapSetRequired=true`, and `ENTITY_REMAP_REQUIRED`. - The live `actor_resource_states` and `actor_active_conditions` tables retain legacy `playable_state_key` rather than the target namespace identity and are not included in the current shallow family enumeration. Their current repositories and validation path therefore do not prove namespace isolation, source-instance coverage, or version-aware classification. Cutover readers must keep both families blocking/unclassified until a namespace-aware migration and owner-local validation registers them explicitly as `S1` or `S2`; the target classification above does not claim this is implemented. - When template-bound `S2` rows exist within that resolved namespace and scope evidence and the caller supplies the frozen approved `remapSetId`, the current implementation reports `COMPATIBLE` and echoes that id. This result is non-authoritative and remains blocking for cutover: no caller or consumer may treat the echoed identifier as admissible compatibility or cleanup proof. Entity Management must validate and apply the exact Game Design-approved mapping locally before acknowledging compatibility. Entity Management does not infer remaps or create a second remap identity; Game Design remains the source of truth for approval and the prepared cutover artifact binds the exact id used. @@ -126,7 +127,7 @@ Cutover fence contract: Illustrative responses for the current live first slice: -- The current request carries `tenant_id`, `source_game_instance_id`, and `target_version_id` as positive decimal strings (for example, `"7"`, `"42"`, and `"43"`), which the service parses to numeric internal IDs; `remap_set_id` is optional text. The response below is only the live `ValidateEntityUpgradeMappingsResponse`: it does not echo tenant/source/target identifiers and exposes no target-only namespace, scope, fence, or classification fields. Its `stateClassesChecked` and `checkedFamilies` fields are aggregate current-response fields: `checkedFamilies` contains emitted family names, including the live spelling `characters`, and carries no per-family outcome. The live `hasS2Rows` calculation uses tenant-wide row counts rather than proving rows for the requested source instance, so it is not source-instance cutover evidence. The response is an incomplete, non-authoritative table-level enumeration. The `item_instances` and `item_stacks` entries below are family names consistent with the live `checkedFamilies` response only; they do not provide holder-scoped evidence or establish a synthetic-room-ground-only filter, nor do they classify every row in either table as `S3`. +- The current request carries `tenant_id`, `source_game_instance_id`, and `target_version_id` as positive decimal strings (for example, `"7"`, `"42"`, and `"43"`), which the service parses to numeric internal IDs; `remap_set_id` is optional text. The response below is only the live `ValidateEntityUpgradeMappingsResponse`: it does not echo tenant/source/target identifiers and exposes no target-only namespace, scope, fence, or classification fields. Its `stateClassesChecked` and `checkedFamilies` fields are aggregate current-response fields: `checkedFamilies` contains emitted family names, including the live spelling `characters`, and carries no per-family outcome. The live `hasS2Rows` calculation uses tenant-wide row counts rather than proving rows for the requested source instance, so it is not source-instance cutover evidence. Separately, the live quarantine check counts all quarantined actors for the tenant, independent of `source_game_instance_id`, before remap handling; it returns `INCOMPATIBLE` with `remapSetRequired=false` and no approved remap ID, and a supplied remap cannot clear that blocker. The response is an incomplete, non-authoritative table-level enumeration. The `item_instances` and `item_stacks` entries below are family names consistent with the live `checkedFamilies` response only; they do not provide holder-scoped evidence or establish a synthetic-room-ground-only filter, nor do they classify every row in either table as `S3`. ```json { @@ -143,13 +144,15 @@ Illustrative responses for the current live first slice: ], "hasS2Rows": true, "result": "INCOMPATIBLE", - "remapSetRequired": true, + "remapSetRequired": false, "reasons": [ - "ENTITY_REMAP_REQUIRED: inventory and equipment rows reference durable entity templates and require an approved remapSetId before replacement-instance cutover" + "ENTITY_ACTOR_IDENTITY_QUARANTINED: legacy actor identity lacks exact Account UUID and owner-resolved namespace/scope provenance" ] } ``` +The live protobuf response leaves `remapSetId` unset for this quarantine result; the supplied remap, if any, does not establish trusted provenance or clear the blocker. + Target-state illustrative responses: - Durable rows present but no remap required: diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java index d852782d19..eeb22e6da1 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java @@ -5,8 +5,6 @@ import java.io.IOException; import java.nio.file.Path; import java.util.List; -import org.flywaydb.core.Flyway; -import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.env.YamlPropertySourceLoader; @@ -40,14 +38,4 @@ void allServiceProfilesBindSessionLevelPostgresqlAdvisoryLocks() throws IOExcept .isFalse(); } } - - @Test - void manualFlywayConfigurationUsesSessionLevelPostgresqlAdvisoryLocks() { - var configuration = Flyway.configure(); - var postgresql = - configuration.getConfigurationExtension(PostgreSQLConfigurationExtension.class); - postgresql.setTransactionalLock(false); - - assertThat(postgresql.isTransactionalLock()).isFalse(); - } } From bf03be01430e9f9dd4fd88dfbca584f218960773 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 01:24:25 +1300 Subject: [PATCH 13/39] Defer Entity strong migration lock until validations complete --- ...4__validate_actor_identity_constraints.sql | 19 ++++++++++--------- ...FlywayPostgresqlLockConfigurationTest.java | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql b/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql index 97eb17a563..0a927a7853 100644 --- a/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql +++ b/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql @@ -1,15 +1,6 @@ /* [jooq ignore start] */ ALTER TABLE characters VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull; -/* [jooq ignore stop] */ - -ALTER TABLE characters - ALTER COLUMN character_uuid SET NOT NULL; - -/* [jooq ignore start] */ -ALTER TABLE characters - DROP CONSTRAINT ck_characters_character_uuid_nonnull; - ALTER TABLE characters VALIDATE CONSTRAINT ck_characters_character_uuid_non_nil; @@ -31,3 +22,13 @@ ALTER TABLE characters ALTER TABLE characters VALIDATE CONSTRAINT fk_characters_owner_resolved_namespace_scope; /* [jooq ignore stop] */ + +-- Take the stronger lock only after all validation scans have completed. The validated +-- non-null check remains present so PostgreSQL can avoid another full-table scan. +ALTER TABLE characters + ALTER COLUMN character_uuid SET NOT NULL; + +/* [jooq ignore start] */ +ALTER TABLE characters + DROP CONSTRAINT ck_characters_character_uuid_nonnull; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java index eeb22e6da1..6f3995a989 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.Test; @@ -13,6 +14,21 @@ import org.springframework.core.io.FileSystemResource; class FlywayPostgresqlLockConfigurationTest { + @Test + void identityValidationScansFinishBeforeStrongLockFinalization() throws IOException { + String migration = + Files.readString( + Path.of("src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql")); + int lastValidation = migration.lastIndexOf("VALIDATE CONSTRAINT "); + int setNotNull = migration.indexOf("ALTER COLUMN character_uuid SET NOT NULL"); + int dropProofCheck = migration.indexOf("DROP CONSTRAINT ck_characters_character_uuid_nonnull"); + + assertThat(lastValidation).isGreaterThanOrEqualTo(0); + assertThat(setNotNull).isGreaterThan(lastValidation); + assertThat(dropProofCheck).isGreaterThan(setNotNull); + assertThat(migration).contains("VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull"); + } + @Test void allServiceProfilesBindSessionLevelPostgresqlAdvisoryLocks() throws IOException { for (Path resourcePath : From dff13b57649b5c6a3e3ecd158e5cbbc5ca6db2a8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 03:10:38 +1300 Subject: [PATCH 14/39] Extract authenticated Account runtime identity producer --- .../account-service/api-contracts.md | 13 + .../v1/runtime_account_identity_service.proto | 29 ++ .../accountservice/AccountUuidText.java | 22 ++ .../RuntimeAccountIdentityGrpcService.java | 173 ++++++++++ .../src/main/resources/application-prod.yml | 1 + .../src/main/resources/application.yml | 2 + .../accountservice/AccountUuidTextTest.java | 37 ++ ...timeAccountIdentityGrpcAuthWiringTest.java | 318 ++++++++++++++++++ ...RuntimeAccountIdentityGrpcServiceTest.java | 261 ++++++++++++++ .../RuntimeAccountIdentityEvidence.java | 50 +++ .../RuntimeAccountIdentityEvidenceTest.java | 98 ++++++ 11 files changed, 1004 insertions(+) create mode 100644 protos/account/v1/runtime_account_identity_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 18864c85ea..479a1fb2b2 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,6 +58,8 @@ This Account source-currentness and first-JOIN persistence prerequisite builds o Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). +`ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. + Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. @@ -114,6 +116,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -129,6 +132,16 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. +### Runtime account identity owner read + +`RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity` reads Account's already-persisted canonical UUID and provenance for Account's own row. The protobuf in [`runtime_account_identity_service.proto`](../../../../protos/account/v1/runtime_account_identity_service.proto) is the wire authority; Account does not derive an identity from another owner's key or row. + +The only permitted peers are verified Game Session and Entity Management workload identities in the exact configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. The RPC is exempted by its exact full method name from bearer-token validation because it is workload-only; the listener remains mTLS-only, and the handler verifies the exact peer service and namespace. JWT claims and request metadata do not establish workload identity. + +The request contains exactly `canonical_account_id` and `request_id`; both must be canonical, lower-case, nonnil UUID strings, and unknown fields or invalid/missing values are rejected. The schema-version-1 response contains the configured `target_namespace`, exact echoed `request_id` and `canonical_account_id`, `source_account_row_id`, and `account_uuid_provenance`. The returned source row and provenance must come from the same persisted Account row whose UUID exactly matches the request selector. The numeric row value is provenance only and must not be used as gameplay identity. Account independently verifies that its persisted `account_uuid_source_numeric_id` equals that row's `id` before returning evidence. Account returns no partial evidence when persisted UUID/provenance/source-row evidence is missing, ambiguous, malformed, or inconsistent. + +This read is not an authentication, membership, entitlement, realm-grant, actor-owner, playable-state namespace, or admission decision. It creates no membership or grant and does not select or activate an actor. Game Session and Entity Management retain their respective runtime composition and admission contracts. + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. diff --git a/protos/account/v1/runtime_account_identity_service.proto b/protos/account/v1/runtime_account_identity_service.proto new file mode 100644 index 0000000000..4a07b9bf3a --- /dev/null +++ b/protos/account/v1/runtime_account_identity_service.proto @@ -0,0 +1,29 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Authenticated owner-local read of Account's persisted UUID identity provenance. +service RuntimeAccountIdentityService { + rpc ResolveRuntimeAccountIdentity(ResolveRuntimeAccountIdentityRequest) + returns (ResolveRuntimeAccountIdentityResponse); +} + +message ResolveRuntimeAccountIdentityRequest { + string canonical_account_id = 1; + string request_id = 2; +} + +message ResolveRuntimeAccountIdentityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + // Private Account provenance evidence; never use this row key as gameplay identity. + int64 source_account_row_id = 5; + string account_uuid_provenance = 6; + reserved 7; + reserved "source_numeric_row_id"; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java new file mode 100644 index 0000000000..04a0818452 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/AccountUuidText.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.accountservice; + +import java.util.UUID; + +/** Canonical non-nil UUID text parsing at Account's local transport boundaries. */ +public final class AccountUuidText { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountUuidText() {} + + public static UUID parseOrNull(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java new file mode 100644 index 0000000000..ad77b09762 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; + +/** Authenticated read of Account's exact retained UUID-to-row provenance. */ +@GrpcService +public class RuntimeAccountIdentityGrpcService + extends RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceImplBase { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountRepository accountRepository; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "AccountRepository is an injected internal owner collaborator, not exposed state.") + public RuntimeAccountIdentityGrpcService( + AccountRepository accountRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.accountRepository = accountRepository; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveRuntimeAccountIdentity( + ResolveRuntimeAccountIdentityRequest request, + StreamObserver responseObserver) { + if (!isAllowedRuntimePeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified Game Session or Entity Management workload identity is required") + .asRuntimeException()); + return; + } + + UUID canonicalAccountId = AccountUuidText.parseOrNull(request.getCanonicalAccountId()); + UUID requestId = AccountUuidText.parseOrNull(request.getRequestId()); + if (canonicalAccountId == null + || requestId == null + || !request.getUnknownFields().asMap().isEmpty()) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription( + "Canonical nonnil IDs and the exact metadata request schema are required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = accountRepository.findByAccountUuid(canonicalAccountId); + } catch (IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Account UUID provenance is ambiguous or invalid") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account identity is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Account identity is temporarily unavailable" + : "Account identity could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Account identity could not be read") + .asRuntimeException()); + return; + } + + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No Account identity for exact canonical account ID") + .asRuntimeException()); + return; + } + + Account account = resolved.orElseThrow(); + if (!hasExactPersistedIdentity(account, canonicalAccountId)) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Account UUID provenance does not match its exact persisted source row") + .asRuntimeException()); + return; + } + + responseObserver.onNext( + ResolveRuntimeAccountIdentityResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(workloadNamespace) + .setRequestId(requestId.toString()) + .setCanonicalAccountId(canonicalAccountId.toString()) + .setSourceAccountRowId(account.getId()) + .setAccountUuidProvenance(account.getAccountUuidProvenance().name()) + .build()); + responseObserver.onCompleted(); + } + + private boolean isAllowedRuntimePeer() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !peer.namespace().equals(workloadNamespace)) { + return false; + } + return peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + || peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"); + } + + private static boolean hasExactPersistedIdentity(Account account, UUID canonicalAccountId) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || NIL_UUID.equals(account.getAccountUuid()) + || !canonicalAccountId.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + return false; + } + return AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()); + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index a0058cdd88..130c82c21d 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -76,6 +76,7 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 526520c5d0..027fc23c34 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -40,6 +40,7 @@ firemud: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} account: credentials: cleanup: @@ -102,6 +103,7 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity management: endpoints: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java new file mode 100644 index 0000000000..dc67f3cc10 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.accountservice; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class AccountUuidTextTest { + @Test + void acceptsCanonicalNonNilUuidText() { + String value = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + + assertEquals(UUID.fromString(value), AccountUuidText.parseOrNull(value)); + } + + @ParameterizedTest + @NullSource + @ValueSource( + strings = { + "", + " ", + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "1-1-1-1-1", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "4cae05e8-7a6b-4b14-9d44-665e3eec450b " + }) + void rejectsMissingNumericMalformedNilAndNoncanonicalText(String value) { + assertNull(AccountUuidText.parseOrNull(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java new file mode 100644 index 0000000000..e4c688060e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -0,0 +1,318 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetProfileResponse; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.RuntimeAccountIdentityGrpcService; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionClaims; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class RuntimeAccountIdentityGrpcAuthWiringTest { + private static final String IDENTITY_METHOD = + "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; + private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetProfile"; + private static final String ACCOUNT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; + private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final MethodDescriptor< + ResolveRuntimeAccountIdentityRequest, ResolveRuntimeAccountIdentityResponse> + IDENTITY_METHOD_DESCRIPTOR = + unaryMethod( + IDENTITY_METHOD, + ResolveRuntimeAccountIdentityRequest.getDefaultInstance(), + ResolveRuntimeAccountIdentityResponse.getDefaultInstance()); + private static final MethodDescriptor + NONPUBLIC_METHOD_DESCRIPTOR = + unaryMethod( + NONPUBLIC_METHOD, + GetProfileRequest.getDefaultInstance(), + GetProfileResponse.getDefaultInstance()); + + @Test + void exactSameNamespaceRuntimePeersReachReadOnlyHandlerUnderBaseAndProdYaml() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + for (String peerUri : List.of(GAME_SESSION_URI, ENTITY_MANAGEMENT_URI)) { + AccountRepository repository = mock(AccountRepository.class); + Account account = persistedAccount(); + when(repository.findByAccountUuid(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(Optional.of(account)); + RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, "test"); + + DispatchResult result = dispatchIdentityMethod(interceptor, service, peerUri, null); + + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getCanonicalAccountId()) + .isEqualTo(ACCOUNT_UUID); + assertThat(result.observer().response.getSourceAccountRowId()).isEqualTo(42L); + assertThat(result.handlerDispatched()).isTrue(); + verify(repository).findByAccountUuid(UUID.fromString(ACCOUNT_UUID)); + } + }); + } + } + + @Test + void absentWrongAndWrongNamespacePeersAreDeniedBeforeRepositoryReadUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountRepository repository = mock(AccountRepository.class); + RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, "test"); + String privilegedBearer = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of( + "accountId", + ACCOUNT_UUID, + "globalRoles", + List.of("platformAdmin"), + "scopedRoles", + Map.of())); + var validatedBearer = jwtUtil.parseToken(privilegedBearer); + assertThat(SessionClaims.fromJwt(validatedBearer).hasPrivilegedRole()).isTrue(); + + DispatchResult absent = dispatchIdentityMethod(interceptor, service, null, null); + DispatchResult wrongService = + dispatchIdentityMethod( + interceptor, service, "spiffe://firemud/ns/test/sa/account-service", null); + DispatchResult wrongNamespace = + dispatchIdentityMethod( + interceptor, + service, + "spiffe://firemud/ns/other/sa/game-session-service", + null); + DispatchResult bearerWithoutPeer = + dispatchIdentityMethod(interceptor, service, null, privilegedBearer); + + for (DispatchResult denied : + List.of(absent, wrongService, wrongNamespace, bearerWithoutPeer)) { + assertThat(denied.observer().failure).isTrue(); + assertThat(denied.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.handlerDispatched()).isTrue(); + } + verifyNoInteractions(repository); + }); + } + } + + @Test + void unrelatedAccountMethodRemainsBearerProtectedUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(NONPUBLIC_METHOD_DESCRIPTOR); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = + mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(next, never()) + .startCall( + org.mockito.ArgumentMatchers.eq(call), + org.mockito.ArgumentMatchers.any(Metadata.class)); + }); + } + } + + private static Account persistedAccount() { + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(UUID.fromString(ACCOUNT_UUID)); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + account.setAccountUuidSourceNumericId(42L); + return account; + } + + private static DispatchResult dispatchIdentityMethod( + AuthTokenInterceptor interceptor, + RuntimeAccountIdentityGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(IDENTITY_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + TestObserver observer = new TestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ResolveRuntimeAccountIdentityRequest, + ResolveRuntimeAccountIdentityResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ResolveRuntimeAccountIdentityRequest request) { + service.resolveRuntimeAccountIdentity(request, observer); + } + }; + } + }; + ResolveRuntimeAccountIdentityRequest request = + ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(ACCOUNT_UUID) + .setRequestId(REQUEST_UUID) + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new DispatchResult(observer, handlerDispatched.get()); + } + + private static void withConfiguredInterceptor( + boolean productionLayer, + java.util.function.BiConsumer action) { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); + PropertySource accountBase = + yamlLoader + .load( + "account-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(accountBase); + if (productionLayer) { + PropertySource accountProduction = + yamlLoader + .load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addFirst(accountProduction); + } + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Account application config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(IDENTITY_METHOD) + .doesNotContain(NONPUBLIC_METHOD); + action.accept( + context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); + }); + } + + private static < + ReqT extends com.google.protobuf.Message, RespT extends com.google.protobuf.Message> + MethodDescriptor unaryMethod( + String fullMethodName, ReqT requestDefault, RespT responseDefault) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(requestDefault)) + .setResponseMarshaller(ProtoUtils.marshaller(responseDefault)) + .build(); + } + + private record DispatchResult(TestObserver observer, boolean handlerDispatched) {} + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeAccountIdentityResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeAccountIdentityResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..6d2af29a7a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -0,0 +1,261 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.TooManyRowsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.dao.DataAccessResourceFailureException; + +class RuntimeAccountIdentityGrpcServiceTest { + private static final String WORKLOAD_NAMESPACE = "test"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + private final AccountRepository repository = mock(AccountRepository.class); + private final RuntimeAccountIdentityGrpcService service = + new RuntimeAccountIdentityGrpcService(repository, WORKLOAD_NAMESPACE); + + @ParameterizedTest + @ValueSource(strings = {GAME_SESSION_URI, ENTITY_MANAGEMENT_URI}) + void resolvesExactPersistedIdentityForEachAllowedRuntimePeer(String peerUri) { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenReturn( + Optional.of( + account(ACCOUNT_ID, AccountIdentityProvenance.ACCOUNT_V29_MIGRATION, 42L, 42L))); + + TestObserver observer = call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), peerUri); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getSchemaVersion()).isEqualTo(1); + assertThat(observer.value.getTargetNamespace()).isEqualTo(WORKLOAD_NAMESPACE); + assertThat(observer.value.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(observer.value.getCanonicalAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(observer.value.getSourceAccountRowId()).isEqualTo(42L); + assertThat(observer.value.getAccountUuidProvenance()).isEqualTo("ACCOUNT_V29_MIGRATION"); + verify(repository).findByAccountUuid(ACCOUNT_ID); + } + + @Test + void deniesMissingWrongNamespaceAndUntrustedPeerIdentitiesBeforeOwnerRead() { + assertThat(status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/other/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), + "spiffe://firemud/ns/test/sa/social-groups-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { + RuntimeAccountIdentityGrpcService inactiveService = + new RuntimeAccountIdentityGrpcService(repository, ""); + TestObserver observer = new TestObserver(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); + + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + inactiveService.resolveRuntimeAccountIdentity( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), observer)); + + assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsNoncanonicalNilAndOpenMetadataRequestsBeforeOwnerRead() { + assertThat( + status( + call( + request(ACCOUNT_ID.toString().toUpperCase(), REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request("00000000-0000-0000-0000-000000000000", REQUEST_ID.toString()), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call( + request(ACCOUNT_ID.toString(), "00000000-0000-0000-0000-000000000000"), + GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + ResolveRuntimeAccountIdentityRequest openRequest = + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(status(call(openRequest, GAME_SESSION_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + " ", + "42", + "not-a-uuid", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void rejectsInvalidAccountAndRequestUuidTextWithoutOwnerRead(String value) { + assertThat(status(call(request(value, REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(request(ACCOUNT_ID.toString(), value), GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void returnsNotFoundAndFailsClosedForMalformedAmbiguousOrMismatchedProvenance() { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenReturn(Optional.empty()) + .thenThrow(new IllegalStateException("private malformed provenance detail")) + .thenThrow(new TooManyRowsException("private duplicate-row detail")) + .thenReturn( + Optional.of( + account(ACCOUNT_ID, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L, 43L))) + .thenReturn( + Optional.of( + account( + UUID.fromString("a2e1342e-a139-49c6-a460-c8e25f6697ae"), + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + 42L, + 42L))); + + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.NOT_FOUND); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + status(call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void distinguishesTemporaryReadFailureFromInternalReadFailureWithoutLeakingDetails() { + when(repository.findByAccountUuid(ACCOUNT_ID)) + .thenThrow(new DataAccessResourceFailureException("private database endpoint")) + .thenThrow(new IllegalArgumentException("private persistence detail")); + + TestObserver unavailable = + call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + TestObserver internal = + call(request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), GAME_SESSION_URI); + + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failure.getDescription()) + .isEqualTo("Account identity is temporarily unavailable"); + assertThat(status(internal)).isEqualTo(Status.Code.INTERNAL); + assertThat(internal.failure.getDescription()).isEqualTo("Account identity could not be read"); + } + + private static Account account( + UUID accountUuid, AccountIdentityProvenance provenance, Long rowId, Long sourceNumericRowId) { + Account account = new Account(); + account.setId(rowId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(sourceNumericRowId); + return account; + } + + private static ResolveRuntimeAccountIdentityRequest request(String accountId, String requestId) { + return ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(accountId) + .setRequestId(requestId) + .build(); + } + + private TestObserver call(ResolveRuntimeAccountIdentityRequest request, String peerUri) { + TestObserver observer = new TestObserver(); + Runnable invocation = () -> service.resolveRuntimeAccountIdentity(request, observer); + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.failure).isNotNull(); + return observer.failure.getCode(); + } + + private static final class TestObserver + implements StreamObserver { + private ResolveRuntimeAccountIdentityResponse value; + private Status failure; + private boolean completed; + + @Override + public void onNext(ResolveRuntimeAccountIdentityResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java new file mode 100644 index 0000000000..981380c587 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidence.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.common.account; + +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Read-only Account owner evidence for one persisted canonical account identity. + * + *

The retained numeric row values are private provenance evidence, not gameplay identity. This + * record does not establish membership, actor ownership, namespace ownership, or admission. + */ +public record RuntimeAccountIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + long sourceAccountRowId, + String accountUuidProvenance) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public RuntimeAccountIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime account identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalAccountId, "canonicalAccountId"); + if (sourceAccountRowId <= 0L) { + throw new IllegalArgumentException("Account source row identity must be positive"); + } + if (!isRecognizedProvenance(accountUuidProvenance)) { + throw new IllegalArgumentException("Account UUID provenance is not recognized"); + } + } + + private static boolean isRecognizedProvenance(String provenance) { + return "ACCOUNT_V29_MIGRATION".equals(provenance) + || "ACCOUNT_REPOSITORY_INSERT".equals(provenance) + || "ACCOUNT_DATABASE_INSERT".equals(provenance); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a nonnil UUID"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java new file mode 100644 index 0000000000..aab060d32a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.account; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class RuntimeAccountIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsEachCanonicalAccountProvenanceKind() { + assertThat(evidence("ACCOUNT_V29_MIGRATION").sourceAccountRowId()).isEqualTo(73L); + assertThat(evidence("ACCOUNT_REPOSITORY_INSERT").accountUuidProvenance()) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(evidence("ACCOUNT_DATABASE_INSERT").accountUuidProvenance()) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + } + + @Test + void rejectsUnsupportedSchemaNamespaceIdentitySourceRowAndProvenance() { + RuntimeAccountIdentityEvidence valid = evidence("ACCOUNT_V29_MIGRATION"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceAccountRowId(), + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + 0L, + valid.accountUuidProvenance()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + null); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalAccountId(), + valid.sourceAccountRowId(), + "UNKNOWN"); + } + + private static RuntimeAccountIdentityEvidence evidence(String provenance) { + return new RuntimeAccountIdentityEvidence(1, "test", REQUEST_ID, ACCOUNT_ID, 73L, provenance); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + long sourceAccountRowId, + String provenance) { + assertThatThrownBy( + () -> + new RuntimeAccountIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalAccountId, + sourceAccountRowId, + provenance)) + .isInstanceOf(IllegalArgumentException.class); + } +} From 8d88c3ecc156c6862acc0e58262e7ccbdcda23ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:32:00 +1300 Subject: [PATCH 15/39] Isolate Account staging and shared owner-source foundation on develop --- .../account-service/api-contracts.md | 12 + .../account-service/runtime-and-data.md | 2 + .../entity-management-service/README.md | 4 +- .../api-contracts.md | 2 - .../entity-management-service/operations.md | 59 - .../runtime-and-data.md | 26 +- .../gameplay-rules-entities-and-effects.md | 13 +- .../v1/actor_staging_eligibility.proto | 75 ++ .../v1/publication_terminal_service.proto | 22 + ...published_realm_entry_policy_service.proto | 44 + ...canonical_gameplay_roster_owner_read.proto | 83 ++ .../v1/draft_terminal_service.proto | 38 + .../world_published_start_location_read.proto | 60 + .../DemoTenantEntitlementEventV1Codec.java | 435 +++++++ .../dto/DemoTenantEntitlementRequest.java | 121 ++ .../dto/DemoTenantEntitlementSnapshot.java | 92 ++ .../dto/TenantAuthorityEventV1Codec.java | 427 ++++++ ...ountActorStagingEligibilityRepository.java | 340 +++++ ...ccountDemoTenantEntitlementRepository.java | 546 ++++++++ ...AccountTenantAuthorityEventRepository.java | 580 +++++++++ ...ountTenantEntitlementOutboxRepository.java | 211 +++ ...AccountActorStagingEligibilityService.java | 104 ++ .../DemoTenantEntitlementException.java | 31 + ...untActorStagingEligibilityGrpcService.java | 214 +++ .../src/main/resources/application-prod.yml | 1 + .../src/main/resources/application.yml | 3 + ...3__account_protected_demo_entitlements.sql | 427 ++++++ ...account_tenant_authority_source_bridge.sql | 482 +++++++ ...EntitlementPersistenceIntegrationTest.java | 629 +++++++++ .../AccountPostgresIntegrationFixture.java | 63 +- ...ingEligibilityPostgresIntegrationTest.java | 472 +++++++ .../dto/DemoTenantEntitlementCodecTest.java | 207 +++ .../dto/TenantAuthorityEventV1CodecTest.java | 88 ++ ...untTenantAuthorityEventRepositoryTest.java | 147 +++ ...untActorStagingEligibilityServiceTest.java | 143 ++ ...ctorStagingEligibilityGrpcServiceTest.java | 251 ++++ ...ccountActorStagingEligibilityEvidence.java | 434 +++++++ .../DraftAuthorizationFenceBinding.java | 662 ++++++++++ .../common/authoring/DraftBaseReference.java | 36 + .../common/authoring/DraftCommitBinding.java | 454 +++++++ .../WorldDraftTerminalReadEvidence.java | 99 ++ .../WorldDraftTerminalReadGrpcCodec.java | 736 +++++++++++ ...AuthoredWorldLaunchDescriptorEvidence.java | 568 ++++++++ ...thoredWorldReleaseAttestationEvidence.java | 732 +++++++++++ .../CompleteLaunchBindingEvidence.java | 14 + .../GameDesignPublicationTerminalClient.java | 159 +++ ...GameDesignPublicationTerminalEvidence.java | 517 ++++++++ ...DesignPublicationTerminalReadEvidence.java | 140 ++ ...esignPublicationTerminalReadGrpcCodec.java | 57 + ...GrpcServerPeerIdentityCallCredentials.java | 41 + ...ccountPublicationAuthorizationBinding.java | 150 +++ .../AuthoredDraftPublishSelectionBinding.java | 359 +++++ ...GameDesignPublicationOperationBinding.java | 67 + .../PublishedRealmEntryPolicyEvidence.java | 173 +++ ...ublishedRealmEntryPolicyReadGrpcCodec.java | 231 ++++ .../PublishedRealmEntryPolicySetEvidence.java | 816 ++++++++++++ .../common/publication/RealmEntryPolicy.java | 176 +++ .../tenant/AuthoredWorldSourceDigest.java | 147 +++ .../tenant/AuthoredWorldSourceEvidence.java | 63 + .../tenant/RuntimeTenantIdentityEvidence.java | 53 + ...onicalGameplayRosterOwnerReadEvidence.java | 165 +++ ...nicalGameplayRosterOwnerReadGrpcCodec.java | 140 ++ ...onCanonicalInitialAdmissionOwnerProof.java | 66 + ...onicalInitialAdmissionOwnerProofCodec.java | 114 ++ ...eededActorAssignmentOwnerReadEvidence.java | 137 ++ ...ededActorAssignmentOwnerReadGrpcCodec.java | 143 ++ .../firemud/common/world/RoomTemplateRef.java | 22 + .../WorldCanonicalInitialAdmissionHold.java | 391 ++++++ .../WorldDraftStartLocationEvidence.java | 286 ++++ .../WorldPublishedStartLocationEvidence.java | 556 ++++++++ .../WorldPublishedStartLocationGrpcCodec.java | 216 ++++ ...ntActorStagingEligibilityEvidenceTest.java | 142 ++ .../authoring/DraftBaseReferenceTest.java | 47 + .../WorldDraftTerminalReadGrpcCodecTest.java | 891 +++++++++++++ ...PublishedRealmEntryPolicyEvidenceTest.java | 231 ++++ .../AuthoredWorldSourceEvidenceTest.java | 398 ++++++ .../RuntimeTenantIdentityEvidenceTest.java | 121 ++ ...alGameplayRosterOwnerReadEvidenceTest.java | 285 ++++ ...alInitialAdmissionOwnerProofCodecTest.java | 169 +++ ...dActorAssignmentOwnerReadEvidenceTest.java | 198 +++ ...shedRealmEntryPolicyReadGrpcCodecTest.java | 544 ++++++++ ...lishedRealmEntryPolicySetEvidenceTest.java | 636 +++++++++ ...orldCanonicalInitialAdmissionHoldTest.java | 596 +++++++++ .../WorldDraftStartLocationEvidenceTest.java | 156 +++ ...ldPublishedStartLocationGrpcCodecTest.java | 179 +++ .../authoring/DraftCommitBindingTest.java | 224 ++++ .../entity/ActorIdentity.java | 74 -- .../entity/ActorIdentityStatus.java | 6 - .../entitymanagement/entity/Character.java | 1 - .../mapper/CharacterMapper.java | 1 - .../ActorActiveConditionRepository.java | 70 +- .../repository/ActorIdentityRepository.java | 105 -- .../ActorResourceStateRepository.java | 63 +- .../CharacterEquipmentRepository.java | 6 +- .../repository/CharacterFriendRepository.java | 52 +- .../repository/CharacterRepository.java | 104 +- .../QuarantinedActorRetentionRepository.java | 90 -- .../service/ScopedCharacterResolver.java | 24 +- .../service/impl/CharacterServiceImpl.java | 58 +- .../EntityUpgradeValidationServiceImpl.java | 13 +- .../RuntimeInstanceCleanupServiceImpl.java | 44 +- .../src/main/resources/application-prod.yml | 2 - .../src/main/resources/application.yml | 2 - ...__quarantine_unresolved_actor_identity.sql | 172 --- ...ld_actor_identity_indexes_concurrently.sql | 20 - ...tor_identity_indexes_concurrently.sql.conf | 1 - ...4__validate_actor_identity_constraints.sql | 34 - ...tainerInstanceLocationIntegrationTest.java | 46 - .../RetainedActorIdentityIntegrationTest.java | 1152 ----------------- ...FlywayPostgresqlLockConfigurationTest.java | 57 - .../entity/ActorIdentityValueTest.java | 108 -- .../ActorActiveConditionRepositoryTest.java | 120 -- .../ActorResourceStateRepositoryTest.java | 117 -- .../CharacterFriendRepositoryTest.java | 133 -- ...arantinedActorRetentionRepositoryTest.java | 89 -- .../service/ScopedCharacterResolverTest.java | 48 - .../impl/CharacterServiceImplListTest.java | 46 +- .../impl/CharacterServiceImplTest.java | 45 +- .../impl/ContainerServiceImplTest.java | 47 +- .../impl/EquipmentServiceImplTest.java | 49 +- .../service/impl/FriendServiceImplTest.java | 27 +- .../impl/InventoryServiceImplTest.java | 35 +- ...RuntimeInstanceCleanupServiceImplTest.java | 58 - .../src/test/resources/application.yml | 4 - 124 files changed, 20537 insertions(+), 2977 deletions(-) create mode 100644 protos/account/v1/actor_staging_eligibility.proto create mode 100644 protos/game-design/v1/publication_terminal_service.proto create mode 100644 protos/game-design/v1/published_realm_entry_policy_service.proto create mode 100644 protos/game-session/v1/canonical_gameplay_roster_owner_read.proto create mode 100644 protos/world-management/v1/draft_terminal_service.proto create mode 100644 protos/world-management/v1/world_published_start_location_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java create mode 100644 services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql create mode 100644 services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java delete mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java delete mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java delete mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java delete mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java delete mode 100644 services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql delete mode 100644 services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql delete mode 100644 services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf delete mode 100644 services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql delete mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java delete mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 79d8db61cd..8b0e9fe9b7 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -142,6 +142,18 @@ The request contains exactly `canonical_account_id` and `request_id`; both must This read is not an authentication, membership, entitlement, realm-grant, actor-owner, playable-state namespace, or admission decision. It creates no membership or grant and does not select or activate an actor. Game Session and Entity Management retain their respective runtime composition and admission contracts. +### Preseeded actor-staging eligibility owner read + +`AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility` is a read-only Account owner RPC for public-production actor staging. The wire schema in [`actor_staging_eligibility.proto`](../../../../protos/account/v1/actor_staging_eligibility.proto) is authoritative. This is an internal workload surface, not a public REST or Gateway route. + +Only the verified Entity Management workload identity in Account's exact configured workload namespace is accepted: `spiffe://firemud/ns/{namespace}/sa/entity-management-service`. The gRPC listener remains mTLS-only. The exact RPC method is exempt from bearer-token validation because authorization comes from the verified workload peer; request metadata and JWT claims do not establish that identity. The handler is disabled unless `firemud.account.actor-staging-eligibility.enabled` is explicitly true, and the default is false. + +Schema version 1 requires the configured `target_namespace`, canonical nonnil UUID text for `request_id`, `canonical_account_id`, and `canonical_tenant_id`, and the sole supported purpose `PUBLIC_PRODUCTION_STAGING_ONLY`. Unknown request fields and all other schemas, namespaces, IDs, or purposes are rejected. Account reads the requested Account, its recognized UUID provenance and source-row binding, fresh Game Design tenant-source evidence, current membership and pair authority, and the matching committed membership event/checkpoint in one read-only repeatable-read owner snapshot. Missing or contradictory source evidence fails closed. + +The response echoes the exact request scope and includes `CURRENT_AT_REVALIDATION`, observation time, the current Account and membership source fields, and independently domain-separated authority-snapshot and eligibility-decision digests. `STAGING_ELIGIBLE` means only that the observed Account is `ACTIVE`, the membership is `ACTIVE`, and its current source allows gameplay; otherwise the evidence reports `STAGING_INELIGIBLE`. This evidence does not establish that a realm is public, that its entry policy is `PRESEEDED_ONLY`, or that gameplay admission is authorized. It creates no membership, grant, actor, JOIN result, PLAY result, or admission authority. + +The handler returns `PERMISSION_DENIED` for a caller that is not the exact verified workload peer, `INVALID_ARGUMENT` for malformed scope or request shape, and `FAILED_PRECONDITION` when current owner evidence is absent or contradictory. Account source unavailability maps to `UNAVAILABLE`; other read or evidence-production failures map to `INTERNAL`. No partial evidence is returned on failure. + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9e8bf02bec..7159ccc74e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -10,6 +10,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation. New repository-created Accounts and a genuinely new issuer receive these baselines; retained rows are not backfilled. Exact security-relevant Account updates compose source generation, issuance fence, canonical event, and current readback in their owner transaction. The owner-local first-JOIN producer/coordinator retains membership, pair/event, audit, and terminal-operation evidence. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime wiring. Reconciled V40/source-currentness/coordinator proof remains pending; see the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. +Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. Focused unit/controller and PostgreSQL integration proof sources are included; validation and live PostgreSQL execution are deferred, so the RPC is not runtime-ready or admission authority. + Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index 7a8d74b6e3..ee6c681fd2 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,9 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. V1 rows and rows created through legacy numeric-ID paths are `QUARANTINED` unless an exact Account UUID plus Game Design-owner-resolved tenant UUID, namespace, and immutable scope are present; the old numeric `account_id`/`tenant_id` and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output is implemented, but Entity's trusted receiving and actor-provenance binding path is absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. There is no mapping or promotion operation and no canonical roster or PLAY activation. Legacy gameplay roster/name lookups return no actors, actor graph reads bypass stale cache entries and recheck persisted disposition, and the exact UUID-qualified repository lookup is not wired as a runtime admission path. Production scoped inventory, containment, equipment, and actor-state/effect calls still fail closed for legacy actor identities; the conditional service and persistence tests do not establish owner-qualified gameplay admission. Synthetic-ID paths, fixed RPG columns, published entry-policy/descriptor/template resolution, namespace-idempotent auto-provision, and fork-local copy proof remain gaps. - -The focused SQL-isolation fixtures may insert owner-resolved rows to test exact tenant/account/namespace/scope predicates; those rows are fixture evidence only and do not prove an Account or Game Design owner supplied that provenance at runtime. Existing `shared-live`, `instance:`, numeric Account/tenant IDs, names, caller checksums, and Game Session pointers never fill missing UUID provenance. +Persisted rows and realm-aware listing exist, but synthetic-ID paths, fixed RPG columns, published entry-policy/descriptor/template resolution, policy-specific roster handling, namespace-idempotent auto-provision, and fork-local copy proof remain gaps. World-owned `character_location` and `npc_location` tables, together with their authoritative movement, occupancy, and read paths, are target-only. They are absent from the current schema and runtime; current room topology or session bindings do not establish location authority, and Entity Management must not persist a competing location table, field, or cache authority. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 7102d39a74..47464c1037 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -10,8 +10,6 @@ The live crafting REST surface is runtime-reachable but is not a tenant-authoriz The live `CharacterController`, `InventoryController`, `EquipmentController`, and `FriendController` REST handlers are also legacy direct adapters. They remain runtime-reachable behind baseline bearer authentication and their implemented tenant-access checks. -Entity V2 now gives persisted characters a private opaque UUID, but the existing REST/gRPC numeric character identifiers are not aliases for that UUID. Legacy actor creation stores the numeric fields and key as source evidence and leaves the actor quarantined; legacy gameplay roster/name reads fail closed, and scoped gameplay access requires a persisted owner-resolved disposition. No public mapping/resolution RPC or account/tenant/namespace provenance producer is defined by this slice. Account UUID and Game Design-owned tenant UUID/namespace/scope must arrive as owner-backed evidence before canonical roster or PLAY can open. A fixture-created owner-resolved row demonstrates repository SQL isolation only, not runtime ownership proof. - Target crafting REST behavior is an authenticated, tenant-scoped design-time surface (not a player crafting shortcut). Entity must derive or validate the target tenant from the authenticated `SessionContext`, reject a caller-supplied tenant that is absent or different from that context, and use tenant-qualified recipe predicates for every read and update. Result and ingredient item references must resolve to items owned by that same tenant and applicable Draft/version scope before persistence; a recipe, result item, or ingredient from another tenant must fail closed without changing recipe or ingredient rows. The focused proof must cover missing/invalid context, tenant A requesting or updating tenant B's recipe, and tenant A attempting to reference tenant B's result or ingredient item. `ApplyActorCondition` has not yet converged on the target replay contract below. Its current request has no dedicated `effectId`; Game Session places the operation-unique durable effect ID in required `sourceId`, which Entity Management first uses as the `{tenantId, effectId}` key for its durable replay marker and operation-name check. The first application then separately uses the first active-condition row matching `{tenantId, playableStateKey, characterId, sourceType, sourceId}`; that narrower lookup does not compare the complete condition payload on same-operation reuse. Until migration, current `sourceId` values must therefore be unique tenant-wide per intended operation/effect, even though the actor-condition row lookup has the narrower scope. This temporary implementation conflates replay identity with authored/source provenance. The current request also accepts caller-supplied `effectPayloadJson`; because `QueryActorState` currently evaluates persisted condition payloads into gameplay-visible actor state, callers must not treat that caller-supplied payload or payload-driven state as trusted typed-effect authority; the transitional evaluation remains until the target server-resolved typed effect snapshot is persisted and read. This is a transitional implementation gap, not mutation authority. The proto, callers, persistence, and proof must migrate together before additional producers reuse one source across applications. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 4ac96395a8..8e18a05c8f 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -10,65 +10,6 @@ The current replacement-validation path is also narrower than the target contrac At the live enqueue boundary, the current Automation implementation expands each enabled command node over its target entity ids, assigns `commandOrdinal`, and enforces configured bounded per-run and per-entity fan-out with atomic rejection before admission when a bound is exceeded. The current path still does not prove complete durable child/target identity or end-to-end fan-out/replay semantics; the target Command-Handoff Identity and its atomic rejection distinction remain required. `automationDispatchId` alone is not a dedupe key; use the complete Command-Handoff Identity for the target contract. -## V3 Concurrent Index Migration Recovery - -Entity V3 creates `ux_characters_character_uuid_idx` concurrently, then `idx_characters_owner_resolved_roster` concurrently, and finally attaches the first index as the `ux_characters_character_uuid` unique constraint. Follow the [database migration contract](../../system-architecture-database-migrations.md) for migration activation and roll-forward. These local recovery steps preserve all character rows and require writer admission to remain closed and quiesced throughout inspection and recovery. - -Use the deployed Entity `SERVICE_SCHEMA` value, confirm the selected schema, and inspect the exact index definitions, PostgreSQL validity/readiness flags, and any attached constraint before taking action. In `psql`, set `service_schema` to that deployed schema and run: - -```sql -SET search_path TO :"service_schema"; - -SELECT current_schema() AS selected_schema, current_schemas(false) AS search_path_schemas; - -SELECT ns.nspname AS schema_name, - idx.relname AS index_name, - pg_get_indexdef(idx.oid) AS index_definition, - pi.indisvalid, - pi.indisready, - pi.indisunique, - con.conname AS attached_constraint -FROM pg_class AS idx -JOIN pg_namespace AS ns ON ns.oid = idx.relnamespace -JOIN pg_index AS pi ON pi.indexrelid = idx.oid -LEFT JOIN pg_constraint AS con ON con.conindid = idx.oid -WHERE ns.nspname = :'service_schema' - AND idx.relname IN ( - 'ux_characters_character_uuid_idx', - 'idx_characters_owner_resolved_roster', - 'ux_characters_character_uuid' - ) -ORDER BY idx.relname; -``` - -Before a concurrent index build or drop, inspect long-running transactions and blockers in the target database; concurrent index operations can wait on old snapshots and other transactions. This read-only query identifies long-running active transactions and sessions blocking or blocked by another backend: - -```sql -SELECT activity.pid, - activity.usename, - activity.state, - now() - activity.xact_start AS transaction_age, - now() - activity.query_start AS query_age, - activity.wait_event_type, - activity.wait_event, - pg_blocking_pids(activity.pid) AS blocking_pids, - activity.query -FROM pg_stat_activity AS activity -WHERE activity.datname = current_database() - AND activity.pid <> pg_backend_pid() - AND (activity.state <> 'idle' OR cardinality(pg_blocking_pids(activity.pid)) > 0) -ORDER BY activity.xact_start NULLS LAST, activity.query_start NULLS LAST; -``` - -An invalid index may be removed only after confirming it is one of these exact V3 indexes, is unattached to a constraint, and its definition matches the expected V3 object. Use the deployed schema explicitly; run each statement outside a transaction: - -```sql -DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".ux_characters_character_uuid_idx; -DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".idx_characters_owner_resolved_roster; -``` - -Drop only the specific invalid, unattached index confirmed by inspection, then verify it is absent. Do not drop a valid index or the attached `ux_characters_character_uuid` constraint as generic cleanup. A blind Flyway repair-and-migrate is unsafe when an earlier V3 statement succeeded: retrying the whole file may collide with a surviving valid index, and attaching the unique index renames it to the constraint's final name. If either expected index is valid, the final constraint exists, or the observed state is otherwise mixed, stop automatic retry and use an operator-reviewed, phase-specific roll-forward plan that accounts for Flyway history and the exact surviving definitions. Do not delete or rewrite character data to make the migration proceed. - ## Target Replacement Operations Replacement operations use the stable `playableStateNamespaceId` and owner-resolved `playableStateScope` for durable S1/S2 state and the active `gameInstanceId` as a runtime fence; Entity validates the scope and never derives it from the opaque namespace. Explicitly disposable S3 families may remain instance-keyed. Entity must report owner-local classification, mapping validation/application, and cleanup acknowledgement to World Management. Unknown or unregistered families block cutover/termination, and an echoed `remapSetId` is not proof of mapping application. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) own the cross-service decisions; this file records the Entity operational consequence. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 08d96b63dc..b9eaa2b9eb 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -11,17 +11,14 @@ This document defines Entity Management’s runtime model, persistence ownership - The `entitymanagement.mutation.effect.execution{operation,effect_status}` metric distinguishes first apply, replay/no-op, in-progress conflict, reported reuse outcome, and unreadable stored-response outcomes. - This current `{tenantId,effectId}` identity is not the target ADR 0054 participant guard: the replay record persists only the operation/status/payload result and reuse checks only the operation name. It does not yet persist or validate the typed target, namespace/scope/fence, or immutable request digest, and changed operation, target, or request reuse is not yet proven fail-closed. - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. -- Character updates are not currently optimistic CAS: `CharacterRepository` increments `version` and requires an exact tenant/row ID match, `OWNER_RESOLVED` status, and one affected row, but does not compare the old version or bind the update to namespace identity. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. +- Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. -- Entity's standard and production Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. See [GR-3.1 implementation and proof status](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for the current integration evidence and remaining gaps. -- The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. +- The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for rows whose `expires_at` has elapsed, without tenant/namespace/instance predicates or a batch bound. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. -- Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with a persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain every prior column/value and are quarantined with no inferred Account or tenant UUID mapping. Legacy row creation likewise remains quarantined. Entity's exact UUID repository lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows; it has no write/promotion API and is not yet connected to a runtime roster. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design tenant UUID/namespace/scope owner producer is also absent. Canonical roster and PLAY activation therefore remain closed. Fixture-created `OWNER_RESOLVED` rows prove only SQL isolation, not owner-backed runtime provenance. -- Legacy character roster/name reads return no actors, numeric-ID graph reads require a fresh persisted `OWNER_RESOLVED` row and bypass the old character graph cache, and scoped gameplay resolution fails closed instead of translating `shared-live` or `instance:`. Consequently, production scoped inventory, containment, equipment, friend, and actor-state/effect calls do not admit legacy actor identities; no canonical owner-qualified gameplay admission path is connected. Resource/condition repositories additionally gate retained rows by actor disposition, and quarantined conditions are excluded from expiry. Conditional service and holder-persistence tests exercise downstream behavior only after an explicitly mocked test guard and do not prove owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. -- Runtime-instance cleanup treats any target `(tenantId, gameInstanceId)` item-instance, container, item-stack, or room-ground row as unclassified evidence and holds cleanup; legacy holder families lack namespace and disposal provenance, so no row is associated with an actor or classified as disposable from a runtime pointer. A transfer audit also holds cleanup when its existing actor link identifies a quarantined actor and its source or destination runtime matches the target. The typed read uses one tenant/runtime target pair and fails closed if its Boolean result is unavailable. An observed empty target returns zero deletion counts and issues no family deletes; this is only an empty-target observation, not trusted quiescence or authority to dispose a nonempty target. Nonempty cleanup remains closed pending owner classification and a fence. This observation-only boundary avoids a check/delete race from deleting rows after the check. -- `characters` still retains the legacy private numeric account/tenant IDs and `playable_state_key`; only the canonical actor provenance columns are UUID-shaped. `actor_resource_states` also retains legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and holder/containment rows do not yet carry `playableStateNamespaceId` (and some omit `tenant_id`). Those dependent families therefore do not yet enforce target `{tenantUuid, playableStateNamespaceId, domainObjectId}` identity. V2 preserves them without inferred mapping; canonical dependent-row migration and owner-backed namespace isolation remain open. +- The live runtime-instance cleanup path currently deletes room-ground inventory, item stacks, item instances, and container instances by `(tenantId, gameInstanceId)` alone. It does not apply namespace, scope, and holder/container closure or prove S3 classification, so its cleanup acknowledgement is unsafe for replacement until owner-local classification, fencing, and focused proof are complete. +- The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. -- `getWithInventory(characterId)` no longer reads from or populates the legacy `characterGraph` cache; it always performs a fresh persisted `OWNER_RESOLVED` read, so stale cache entries cannot authorize a response. The old ID-only cache has no namespace or authoritative-version validation and must not be reconnected as correctness authority; the target namespace-qualified Class A `character-cache:*` contract remains unimplemented. +- The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. - `EntityDraftDesignDigestServiceImpl` currently emits `digestSchemaVersion=1` without hashing item `equipmentSlotGroupKey`, while `EquipmentServiceImpl` uses that field for slot compatibility admission. The digest is therefore incomplete for equipment semantics: different slot-group constraints may attest the same content digest. Target convergence adds the normalized field, bumps the schema version, and proves cross-version digest isolation plus publish-gate rejection of a changed constraint. ## Architecture and Design Notes @@ -105,7 +102,6 @@ Implementation notes: - The live implementation enumerates tenant-surviving families (`character`, `inventory`, `character_equipment`, `character_friend`) plus the currently persisted families requiring holder classification (`room_ground_inventory`, `item_instances`, `item_stacks`, `container_instances`). The storage/table family `character` is emitted as the plural wire label `characters` in `checkedFamilies`; that is one explicit storage-to-wire mapping, not two families. The mapping should remain canonicalized or explicitly represented in the target family registry. It does not currently enumerate the durable `actor_resource_states` or `actor_active_conditions` families, even though both are live persistence tables and are consumed by actor-state reads/mutations; the current validation response therefore cannot claim complete actor-state classification. - `item_instances` and `item_stacks` are not table-wide `S3` families: each row follows its holder/container graph. A durable player or durable namespace-backed container holder identified by `(tenantId, playableStateNamespaceId)` plus its domain object identity is `S1` or `S2` according to template-remap requirements; `playableStateScope` remains a separately validated predicate, and only a synthetic room-ground holder or another explicitly instance-scoped holder is `S3`. Termination cleanup must apply the holder/container, namespace, and scope predicates and must not delete all rows in either table by `gameInstanceId` alone. The current table-level enumeration does not yet prove this predicate, so this remains an implementation/proof gap rather than permission to classify durable inventory as `S3`. - `character` and `character_friend` rows have the target `S1` survivor classification within the resolved `(tenantId, playableStateNamespaceId)` identity and immutable scope evidence, and their presence does not require a remap set by itself. At the current boundary this classification is provisional: the live `character`/`character_friend` data is not namespace-isolated proof while legacy `playable_state_key`/namespace-free rows remain, so cutover readers must fail closed or require the completed migration, namespace-aware predicates, and focused isolation proof before treating either family as namespace-backed. -- The live cutover validator counts quarantined characters by tenant through `countQuarantinedByTenantId`, independent of `sourceGameInstanceId`, before evaluating the optional remap. Any such row returns `INCOMPATIBLE` with `ENTITY_ACTOR_IDENTITY_QUARANTINED`, `remapSetRequired=false`, and no approved remap ID; supplying a remap cannot clear the quarantine result. Cutover remains blocked until trusted actor provenance is established. This records current behavior and does not change runtime behavior or expand the target contract. - **Target classification:** `inventory` and `character_equipment` rows are `S2` template-bound survivor state only within the resolved `(tenantId, playableStateNamespaceId)` identity and immutable scope evidence. The current schema has no namespace column for these families, so the live tenant-wide `hasS2Rows` count cannot establish that rows belong to the requested namespace/source instance and is non-authoritative cutover evidence; a namespace-bound implementation must first prove the rows' scope. Under the target contract, if either family has rows in that resolved namespace and no approved `remapSetId` was frozen by launch resolution, validation returns `result=INCOMPATIBLE`, `hasS2Rows=true`, `remapSetRequired=true`, and `ENTITY_REMAP_REQUIRED`. - The live `actor_resource_states` and `actor_active_conditions` tables retain legacy `playable_state_key` rather than the target namespace identity and are not included in the current shallow family enumeration. Their current repositories and validation path therefore do not prove namespace isolation, source-instance coverage, or version-aware classification. Cutover readers must keep both families blocking/unclassified until a namespace-aware migration and owner-local validation registers them explicitly as `S1` or `S2`; the target classification above does not claim this is implemented. - When template-bound `S2` rows exist within that resolved namespace and scope evidence and the caller supplies the frozen approved `remapSetId`, the current implementation reports `COMPATIBLE` and echoes that id. This result is non-authoritative and remains blocking for cutover: no caller or consumer may treat the echoed identifier as admissible compatibility or cleanup proof. Entity Management must validate and apply the exact Game Design-approved mapping locally before acknowledging compatibility. Entity Management does not infer remaps or create a second remap identity; Game Design remains the source of truth for approval and the prepared cutover artifact binds the exact id used. @@ -127,7 +123,7 @@ Cutover fence contract: Illustrative responses for the current live first slice: -- The current request carries `tenant_id`, `source_game_instance_id`, and `target_version_id` as positive decimal strings (for example, `"7"`, `"42"`, and `"43"`), which the service parses to numeric internal IDs; `remap_set_id` is optional text. The response below is only the live `ValidateEntityUpgradeMappingsResponse`: it does not echo tenant/source/target identifiers and exposes no target-only namespace, scope, fence, or classification fields. Its `stateClassesChecked` and `checkedFamilies` fields are aggregate current-response fields: `checkedFamilies` contains emitted family names, including the live spelling `characters`, and carries no per-family outcome. The live `hasS2Rows` calculation uses tenant-wide row counts rather than proving rows for the requested source instance, so it is not source-instance cutover evidence. Separately, the live quarantine check counts all quarantined actors for the tenant, independent of `source_game_instance_id`, before remap handling; it returns `INCOMPATIBLE` with `remapSetRequired=false` and no approved remap ID, and a supplied remap cannot clear that blocker. The response is an incomplete, non-authoritative table-level enumeration. The `item_instances` and `item_stacks` entries below are family names consistent with the live `checkedFamilies` response only; they do not provide holder-scoped evidence or establish a synthetic-room-ground-only filter, nor do they classify every row in either table as `S3`. +- The current request carries `tenant_id`, `source_game_instance_id`, and `target_version_id` as positive decimal strings (for example, `"7"`, `"42"`, and `"43"`), which the service parses to numeric internal IDs; `remap_set_id` is optional text. The response below is only the live `ValidateEntityUpgradeMappingsResponse`: it does not echo tenant/source/target identifiers and exposes no target-only namespace, scope, fence, or classification fields. Its `stateClassesChecked` and `checkedFamilies` fields are aggregate current-response fields: `checkedFamilies` contains emitted family names, including the live spelling `characters`, and carries no per-family outcome. The live `hasS2Rows` calculation uses tenant-wide row counts rather than proving rows for the requested source instance, so it is not source-instance cutover evidence. The response is an incomplete, non-authoritative table-level enumeration. The `item_instances` and `item_stacks` entries below are family names consistent with the live `checkedFamilies` response only; they do not provide holder-scoped evidence or establish a synthetic-room-ground-only filter, nor do they classify every row in either table as `S3`. ```json { @@ -144,15 +140,13 @@ Illustrative responses for the current live first slice: ], "hasS2Rows": true, "result": "INCOMPATIBLE", - "remapSetRequired": false, + "remapSetRequired": true, "reasons": [ - "ENTITY_ACTOR_IDENTITY_QUARANTINED: legacy actor identity lacks exact Account UUID and owner-resolved namespace/scope provenance" + "ENTITY_REMAP_REQUIRED: inventory and equipment rows reference durable entity templates and require an approved remapSetId before replacement-instance cutover" ] } ``` -The live protobuf response leaves `remapSetId` unset for this quarantine result; the supplied remap, if any, does not establish trusted provenance or clear the blocker. - Target-state illustrative responses: - Durable rows present but no remap required: @@ -309,7 +303,7 @@ See [Versioning & Runtime Configuration](../../system-architecture-versioning-ru - The first shared effect-evaluation seam is an in-process Entity Management service that evaluates typed resource modifiers and granted states deterministically. Active condition payloads and equipped item-template payloads are `CONTINUOUS` effect sources: they contribute while their source exists and never write derived values into current resources during reads. When an attached source changes a bounded-resource maximum, its attach, detach, refresh, expiry, or replacement mutation performs the one idempotent capacity normalization using the declaration override or resolved tenant/game `actorState.capacityChangePolicy` captured by that mutation. Evaluation reads never normalize current state. Gameplay-attested `ApplyActorCondition` calls are the first `INSTANT` mutation path, creating active condition/action-state rows through the same internal mutation service under an idempotent effect id. A scheduled Entity Management job globally and without a batch bound deletes elapsed active-condition rows on a 30-second default fixed delay measured after the previous invocation completes; read-time filtering prevents expired effects from being restored before cleanup. The job does not delete separate `entity_mutation_effects` receipts, which are checked before mutation, but receipt-retention and typed replay/concurrency proof remain target gaps. Player command wiring remains future work. - Target-state active-condition rows are condition instances with stable instance ids, frozen definition/release snapshots, source provenance, stack counts, expiry, and applied-effect snapshots. Condition-definition DML, not source-id coincidence, selects `REPLACE`, `REFRESH`, `STACK`, or `PARALLEL` reapplication behavior and its duration policy. Typed removal resolves exact keys, authored tags, or permitted sources in deterministic definition priority and instance-id order; it must not expose raw row or payload deletion to player-facing callers. - Target only: World Management will own character/NPC location and instance-membership rows and their authoritative reads/writes; those tables and paths are not present in the current implementation. Entity Management owns and persists item instances and inventories, but must not add competing actor-location fields or tables. -- Target only: Entity graphs will cache namespace-qualified inventory relationships under the [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md) contract. `getWithInventory` currently bypasses the legacy graph cache and reads persisted owner-resolved state, as recorded in [implementation status](#implementation-status). +- Entity graphs cache inventory relationships for fast lookups. ### Persisted actor and realm-entry identity @@ -423,7 +417,7 @@ Operators and later fraud/dupe-detection tooling should also be able to derive l Synthetic room-ground containers scoped by `(tenantId, gameInstanceId, roomInstanceId)` must be removed through the durable Temporal `world-lifecycle` termination flow described in World Management docs: - Game Session must already have closed admissions for the target instance before cleanup starts. -- Entity Management owns cleanup of containers and contained items for a terminating `gameInstanceId`; the current implementation cannot authorize deletion of nonempty legacy holder families until their owner classification and cleanup fence are established. +- Entity Management owns cleanup of containers and contained items for a terminating `gameInstanceId`. - Cleanup must be idempotent and guarded by a durable workflow step key so retries converge without double-deletes. - Entity Management must not treat world row deletion as implicit cleanup confirmation; World Management marks an instance `TERMINATED` only after this service confirms cleanup completion. - Entity Management must register every additional `gameInstanceId`-owned family, its S3 classification, cleanup request identity, retention rule, and acknowledgement status with the lifecycle owner. Missing or unregistered Entity families block `TERMINATED`; cleanup of one known room-ground family is not whole-service completion. Namespace-backed S1/S2 state under `(tenantId, playableStateNamespaceId)` plus its domain object identity is retained or mapped under the replacement contract; the immutable `playableStateScope` remains separately validated and must not be reinterpreted, and that state is not deleted merely because one runtime instance ended. See [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 19b2742022..bb22de602f 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -26,12 +26,12 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity V2 allocates opaque character UUIDs and retains V1 source values, but unresolved actors remain quarantined; canonical owner-backed roster and PLAY stay closed. The inherited #2965 Account UUID registration/export output is implemented, but trusted receiving and actor-provenance binding in Entity are absent; the Game Design-owned tenant UUID/namespace/scope producer, policy/descriptor/template resolution, unified actor runtime, and complete respawn lifecycle remain absent. | `audited` - Prior-head CI run 37165391640 executed all nine Entity integration tests against PostgreSQL 16.15 with zero failures or skips, including the five retained-actor cases then present. The current retained-actor class has eight cases and the Entity integration tree has twelve; execution of this current suite remains pending, not proved by that historical run. This is executed bounded migration, SQL-isolation, and runtime-quarantine proof; fixture-created `OWNER_RESOLVED` rows exercise SQL predicates only and do not establish owner-backed runtime provenance. The corrected Entity unit suite passed 208 tests in 40 suites with zero failures, errors, or skips; trusted owner-backed runtime provenance and PLAY remain unproved. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Existing numeric account/tenant and `playable_state_key` values remain source evidence only; no mapping is inferred and no runtime resolver can promote them. Beyond the V2 retention/isolation foundation, synthetic-ID risk, fixed RPG-shaped fields, realm-authored policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open. | -| GR-3.2 Inventory, containers, ownership, and placement | `partial` - holder records and inventory/container/transfer/replay code exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution also bypasses the Entity replay ledger. | `audited` - focused service tests cover conditional downstream holder behavior; `ContainerInstanceLocationIntegrationTest` preserves PostgreSQL-backed nested-holder/persistence assertions behind a fixture-mocked exact scope guard for quarantined saved characters. It is conditional domain proof, not owner provenance or runtime admission proof. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Canonical owner-qualified runtime admission, blank-`effectId` ingress remediation, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting remain open. | -| GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - equipment service/controller code and authored slot/body-layout checks exist, but production actor-scoped `WEAR`/`REMOVE` admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment tests cover conditional slot compatibility and binding behavior, not production owner-qualified actor admission or PLAY access. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, owner-qualified runtime admission, and owner-validated cutover remapping remain gaps coordinated with AR-3.2. | -| GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - deterministic evaluator, condition mutation, and replay components exist, but scoped Entity actor-state/effect admission remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `audited` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Canonical actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - durable character, NPC, and item records plus bounded XP and NPC respawn-eligibility checks exist; Entity is the target persisted actor owner, but policy-aware entry, unified actor runtime, and complete respawn lifecycle do not. | `proven` - focused character, NPC, and item/inventory tests cover bounded records and lifecycle seams, not PLAYER-01 policy/copy proof. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Synthetic-ID risk, fixed RPG-shaped fields, published policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain unproven. | +| GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | +| GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | +| GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | | GR-4.2 Combat and conflict resolution | `not-implemented` - no combat/conflict resolver or authoritative combat loop is present. | `audited` - adjacent action-state/effect tests were inspected, but no focused combat proof exists. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md) | No production anchor: no combat owner is implemented. Adjacent context only: [ActionStateCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) and [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java) are non-combat seams. | No focused executable proof. [ActionStateCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java) is legacy context for the removed transient action-state handler path, not current combat proof; this does not mean the live durable `BLOCK` gameplay command or its replay-record category was removed. | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [GR-1.2](./game-session-runtime-and-tick-coordination.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Damage packets, hit/mitigation ordering, combat timing, body-region resolution, and combat-driven defeat/loot/revival/victory behavior remain absent. | -| GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads exist, but production XP/level mutation remains fail-closed pending owner-qualified actor resolution; ability and skill progression is not implemented. | `audited` - focused character progression and actor-state tests prove bounded service behavior with a mocked resolver; this conditional proof does not establish production owner-qualified admission. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | +| GR-4.3 Abilities, advancement, and progression | `partial` - character XP/level-up mutation and actor-state level/experience reads are live; ability and skill progression is not. | `proven` - focused character progression and actor-state tests cover the bounded XP/level seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java) | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [EA-3.1](./player-experience-commands-and-communication.md) | No release-pinned ability/skill catalog, authored advancement rules, resource/cooldown progression, or player ability flow is implemented. | | GR-4.4 In-game economy, trading, crafting, and exchange | `partial` - version-scoped recipe/ingredient persistence and CRUD APIs exist; gameplay crafting, economy, trading, and exchange do not. | `proven` - focused crafting controller/service tests cover recipe persistence and validation; item transfer tests cover only the adjacent substrate. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Entity API current status](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status) | [CraftingServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImpl.java); [CraftingController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CraftingController.java); [CraftingRecipe.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CraftingRecipe.java); [crafting schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [CraftingServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CraftingServiceImplTest.java); [CraftingControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CraftingControllerTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Material consumption/result creation, currency and vendor policy, trade/exchange flows, and end-to-end player proof remain absent. | ## Canonical Design Sources @@ -126,8 +126,7 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); accepted generated-child allocation is defined in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); its implementation and proof remain incomplete. This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. - [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md) and [ADR 0061](../../architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md) keep ambient/location facts in World, item holders in Entity, and root outcomes/reconciliation in Game Session. Current gameplay has no complete cross-owner mutation/targeting proof; the accepted ownership direction does not promote current item or movement seams. -- Guarded administrative inventory/equipment mutation handlers require scoped actor resolution, which unconditionally denies legacy actor identities before persistence; these guarded paths cannot currently write `ItemInstance` or `ItemStack`. They remain outside Game Session effect, tick, and barrier admission, and the code does not establish an approved owner/admin contract. -- Separately, the crafting REST adapter remains runtime-reachable unsupported implementation drift: it lacks tenant binding and trusts request-supplied tenant and item identifiers. The details and target boundary remain in [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). +- Reachable tenant-access-checked administrative `POST`/`DELETE` inventory/equipment mutation handlers persist `ItemInstance` and `ItemStack` through Entity outside Game Session effect, tick, and barrier admission and do not require character ownership. `ScopedCharacterResolver` verifies tenant, character, and playable-state scope; persistence outside Game Session admission remains a gap. The current paths do not establish an admin-role check or an approved owner/admin contract. - Broader gameplay families remain unimplemented or unproved against the target contracts owned by [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and the canonical [Transactions generated-effect-chain contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The parent inventory slice remains partially implemented as a domain: manual happy-path verification over both WebSocket and Telnet is still unchecked, and later nested-container UX, crafting/material flows, banking/vendor/mail/trade, loot generation, scripted item behavior, durability, and richer client filtering are not implemented. diff --git a/protos/account/v1/actor_staging_eligibility.proto b/protos/account/v1/actor_staging_eligibility.proto new file mode 100644 index 0000000000..4096fce8e9 --- /dev/null +++ b/protos/account/v1/actor_staging_eligibility.proto @@ -0,0 +1,75 @@ +syntax = "proto3"; + +package account.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Read-only Account evidence for non-admitting, public-production actor staging. +service AccountActorStagingEligibilityService { + rpc ResolvePreseededActorStagingEligibility( + ResolvePreseededActorStagingEligibilityRequest) + returns (ResolvePreseededActorStagingEligibilityResponse); +} + +enum ActorStagingEligibilityPurpose { + ACTOR_STAGING_ELIGIBILITY_PURPOSE_UNSPECIFIED = 0; + PUBLIC_PRODUCTION_STAGING_ONLY = 1; +} + +enum ActorStagingEligibilityDecision { + ACTOR_STAGING_ELIGIBILITY_DECISION_UNSPECIFIED = 0; + STAGING_ELIGIBLE = 1; + STAGING_INELIGIBLE = 2; +} + +enum ActorStagingEligibilityCurrentness { + ACTOR_STAGING_ELIGIBILITY_CURRENTNESS_UNSPECIFIED = 0; + CURRENT_AT_REVALIDATION = 1; +} + +message ResolvePreseededActorStagingEligibilityRequest { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + string canonical_tenant_id = 5; + ActorStagingEligibilityPurpose purpose = 6; +} + +// This response is a current Account and membership snapshot only. It does not assert that a +// realm is public, that its entry policy is PRESEEDED_ONLY, or that gameplay admission is allowed. +message ResolvePreseededActorStagingEligibilityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string canonical_account_id = 4; + string canonical_tenant_id = 5; + ActorStagingEligibilityPurpose purpose = 6; + ActorStagingEligibilityCurrentness currentness = 7; + google.protobuf.Timestamp observed_at = 8; + ActorStagingEligibilityDecision decision = 9; + + string account_uuid_provenance = 10; + string account_lifecycle_state = 11; + + string membership_lifecycle_state = 12; + bool gameplay_admission_allowed = 13; + string membership_authority_provenance = 14; + int64 membership_version = 15; + int64 membership_authority_generation = 16; + string tenant_provenance_kind = 17; + string tenant_source_operation_id = 18; + string tenant_provenance_digest = 19; + + int64 membership_event_sequence = 20; + string membership_event_id = 21; + string membership_event_digest = 22; + bool last_transition_invalidated = 23; + + // Bare lowercase SHA-256 hex values, domain-separated by digest purpose. + string eligibility_decision_digest = 24; + string authority_snapshot_digest = 25; +} diff --git a/protos/game-design/v1/publication_terminal_service.proto b/protos/game-design/v1/publication_terminal_service.proto new file mode 100644 index 0000000000..c071aad909 --- /dev/null +++ b/protos/game-design/v1/publication_terminal_service.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Explicit composition only; no runtime publication or lifecycle authority is enabled. +service GameDesignPublicationTerminalReadService { + rpc ReadGameDesignPublicationTerminal(ReadGameDesignPublicationTerminalRequest) + returns (ReadGameDesignPublicationTerminalResponse); +} + +message ReadGameDesignPublicationTerminalRequest { + // Closed schema-1 namespace/read UUID/complete original operation carrier. + bytes canonical_request_bytes = 1; +} + +message ReadGameDesignPublicationTerminalResponse { + // Exact request echo plus UNKNOWN or the unchanged immutable terminal evidence. + bytes canonical_response_bytes = 1; +} diff --git a/protos/game-design/v1/published_realm_entry_policy_service.proto b/protos/game-design/v1/published_realm_entry_policy_service.proto new file mode 100644 index 0000000000..749d3d9ca7 --- /dev/null +++ b/protos/game-design/v1/published_realm_entry_policy_service.proto @@ -0,0 +1,44 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Exact same-namespace Game Session workload only; explicit composition, not runtime registration. +service PublishedRealmEntryPolicyService { + rpc ResolvePublishedRealmEntryPolicy(ResolvePublishedRealmEntryPolicyRequest) + returns (ResolvePublishedRealmEntryPolicyResponse); + rpc ListPublishedRealmEntryPolicies(ListPublishedRealmEntryPoliciesRequest) + returns (ListPublishedRealmEntryPoliciesResponse); +} + +message ResolvePublishedRealmEntryPolicyRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; + string world_slug = 6; + string realm_slug = 7; +} + +message ResolvePublishedRealmEntryPolicyResponse { + ResolvePublishedRealmEntryPolicyRequest request = 1; + // Complete immutable set proves the selected row without weakening its publication binding. + bytes policy_set_evidence = 2; +} + +message ListPublishedRealmEntryPoliciesRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; +} + +message ListPublishedRealmEntryPoliciesResponse { + ListPublishedRealmEntryPoliciesRequest request = 1; + // Complete ordered set, count/digests and exact actual source/capture/terminal/release evidence. + bytes policy_set_evidence = 2; +} diff --git a/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto new file mode 100644 index 0000000000..55fb7b93d4 --- /dev/null +++ b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto @@ -0,0 +1,83 @@ +syntax = "proto3"; + +package game_session.v1; + +option java_multiple_files = true; +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_outer_classname = "CanonicalGameplayRosterOwnerReadProto"; + +// Entity-only source read for a fresh public-production SHARED route and its complete sealed +// PRESEEDED_ONLY Game Design policy set. This read is not Account membership, PLAY admission, or +// actor-entry authorization. +service CanonicalGameplayRosterOwnerReadService { + rpc GetCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest) + returns (GetCanonicalGameplayRosterOwnerReadResponse); + rpc GetPreseededActorAssignmentOwnerRead( + GetPreseededActorAssignmentOwnerReadRequest) + returns (GetPreseededActorAssignmentOwnerReadResponse); +} + +// All UUID selectors are canonical non-nil UUID strings. Counters are positive signed int64s; +// callers must send the exact current values they observed and may not infer a version from them. +message GetCanonicalGameplayRosterOwnerReadRequest { + uint32 schema_version = 1; + string request_uuid = 2; + // Echo/binding only. Account remains the authority for membership and entitlements. + string canonical_account_uuid = 3; + string target_namespace = 4; + string canonical_tenant_uuid = 5; + string world_slug = 6; + string realm_uuid = 7; + string realm_slug = 8; + string playable_state_namespace_uuid = 9; + string playable_state_scope = 10; + string canonical_game_instance_uuid = 11; + string canonical_version_uuid = 12; + int64 expected_catalog_revision = 13; + int64 expected_pointer_version = 14; + int64 expected_active_world_epoch = 15; +} + +// Successful responses echo the entire request and carry the complete canonical bytes of the +// existing Game Session World-hold-bound COMMITTED proof and Game Design sealed policy set, plus +// the Game Session-owned current-pointer snapshot digest. +message GetCanonicalGameplayRosterOwnerReadResponse { + GetCanonicalGameplayRosterOwnerReadRequest request = 1; + bytes game_session_owner_proof = 2; + bytes published_policy_set_evidence = 3; + // Raw lowercase SHA-256 of the GS-owned canonical current-pointer projection, not the commit proof digest. + string admission_pointer_snapshot_digest = 4; +} + +// Assignment staging selects a canonical tenant and exact immutable target selectors. Game +// Session derives current pointer and World epoch counters from its owner rows; callers do not send +// guessed or stale counters. This source read is not Account membership, JOIN, PLAY, or admission. +message GetPreseededActorAssignmentOwnerReadRequest { + uint32 schema_version = 1; + string assignment_uuid = 2; + // Echo/binding only. Account remains the authority for staging eligibility. + string canonical_account_uuid = 3; + string target_namespace = 4; + string canonical_tenant_uuid = 5; + string world_slug = 6; + string realm_uuid = 7; + string realm_slug = 8; + string playable_state_namespace_uuid = 9; + string playable_state_scope = 10; + string canonical_game_instance_uuid = 11; + string canonical_version_uuid = 12; + int64 expected_catalog_revision = 13; + string expected_policy_digest = 14; + string expected_published_release_bundle_ref = 15; +} + +// Successful responses echo the selector request and carry the complete canonical bytes of the +// existing Game Session World-hold-bound COMMITTED proof and Game Design sealed policy set, plus +// the Game Session-owned current-pointer snapshot digest. +message GetPreseededActorAssignmentOwnerReadResponse { + GetPreseededActorAssignmentOwnerReadRequest request = 1; + bytes game_session_owner_proof = 2; + bytes published_policy_set_evidence = 3; + string admission_pointer_snapshot_digest = 4; +} diff --git a/protos/world-management/v1/draft_terminal_service.proto b/protos/world-management/v1/draft_terminal_service.proto new file mode 100644 index 0000000000..b839e55728 --- /dev/null +++ b/protos/world-management/v1/draft_terminal_service.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of immutable World Draft terminal evidence. +service WorldDraftTerminalReadService { + rpc ReadWorldDraftTerminalOutcome(ReadWorldDraftTerminalOutcomeRequest) + returns (ReadWorldDraftTerminalOutcomeResponse); +} + +enum WorldDraftTerminalReadStatus { + WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED = 0; + WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN = 1; + WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED = 2; + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED = 3; +} + +message ReadWorldDraftTerminalOutcomeRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account fence bytes; this is read identity, not permission. + bytes original_account_binding = 4; +} + +message ReadWorldDraftTerminalOutcomeResponse { + // The complete request tuple is echoed byte-for-byte, including the original Account binding. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_account_binding = 4; + WorldDraftTerminalReadStatus status = 5; + // Canonical account-draft-owner-readback/v1 bytes. Empty only for UNKNOWN. + bytes owner_readback_bytes = 6; +} diff --git a/protos/world-management/v1/world_published_start_location_read.proto b/protos/world-management/v1/world_published_start_location_read.proto new file mode 100644 index 0000000000..571992c5f2 --- /dev/null +++ b/protos/world-management/v1/world_published_start_location_read.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of the selector in an exact frozen World publication capture. +service WorldPublishedStartLocationReadService { + rpc ReadWorldPublishedStartLocation(ReadWorldPublishedStartLocationRequest) + returns (ReadWorldPublishedStartLocationResponse); +} + +message WorldPublishedStartLocationAffectedTuple { + string owner = 1; + string aggregate_type = 2; + string aggregate_id = 3; + string scope_type = 4; + string scope_id = 5; + string expected_epoch = 6; +} + +message ReadWorldPublishedStartLocationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; +} + +message ReadWorldPublishedStartLocationResponse { + // Exact echo of the complete immutable frozen selection request. + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; + // Exact original World receipt, Account binding, and APPLIED result bytes. + bytes selector_receipt_bytes = 15; + bytes original_account_binding_bytes = 16; + bytes applied_result_bytes = 17; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java new file mode 100644 index 0000000000..e5a77be1b4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java @@ -0,0 +1,435 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical Account event encoding for explicit non-paid demo entitlements. */ +public final class DemoTenantEntitlementEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-entitlement-event/v1"; + public static final String EVENT_TYPE = "TENANT_ENTITLEMENT_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "outboxStreamKey", + "tenantId", + "tenantBillingSequence", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "entitlementVersion", + "entitlementKind", + "status", + "subscriptionStatus", + "paid", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "sourceEvidence", + "eventDigest"); + private static final Set QUOTA_FIELDS = + Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"); + private static final java.util.regex.Pattern DIGEST = + java.util.regex.Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,18})"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private DemoTenantEntitlementEventV1Codec() {} + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence) { + if (request == null || source == null) { + throw new IllegalArgumentException( + "Demo entitlement request and source evidence are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest())) { + throw new IllegalArgumentException( + "Demo entitlement event source differs from exact request"); + } + UUID eventId = eventId(request.requestId()); + String streamKey = + AccountTenantEntitlementOutboxRepository.streamKey(request.canonicalTenantId()); + Map preimage = + eventFields( + request, + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + eventId, + streamKey); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas(), + eventId, + streamKey, + digest, + payload); + } + + /** Parses and verifies the exact canonical event payload stored in Account's outbox. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Demo entitlement event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Demo entitlement event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = canonical(preimage); + if (!claimedDigest.equals(digest(canonicalPreimage))) { + throw new IllegalArgumentException( + "Demo entitlement event digest does not match its payload"); + } + if (!java.util.Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Demo entitlement event payload is not canonical JSON"); + } + + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID actualEventId = uuid(wire.get("eventId"), "eventId"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + if (!SCHEMA_VERSION.equals(wire.get("schemaVersion")) + || !EVENT_TYPE.equals(wire.get("eventType")) + || !"NON_PAID_DEMO".equals(wire.get("entitlementKind")) + || !"ACTIVE".equals(wire.get("status")) + || wire.get("subscriptionStatus") != null + || !Boolean.FALSE.equals(wire.get("paid")) + || !DIGEST.matcher(text(wire.get("requestDigest"), "requestDigest")).matches() + || !eventId(requestId).equals(actualEventId) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(streamKey)) { + throw new IllegalArgumentException( + "Demo entitlement event identity or non-paid state is invalid"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + text(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + text(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement event source targets another tenant"); + } + + Map quotaMap = object(wire.get("quotas"), "quotas"); + if (!quotaMap.keySet().equals(QUOTA_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event quota fields are incomplete"); + } + DemoTenantEntitlementRequest.Quotas quotas = + new DemoTenantEntitlementRequest.Quotas( + nonnegativeDecimal(quotaMap.get("maxActiveSessions"), "maxActiveSessions"), + nonnegativeDecimal( + quotaMap.get("maxConcurrentGameInstances"), "maxConcurrentGameInstances"), + nonnegativeDecimal(quotaMap.get("maxStorageBytes"), "maxStorageBytes")); + + return new Event( + requestId, + text(wire.get("requestDigest"), "requestDigest"), + tenantId, + source, + positiveDecimal(wire.get("entitlementVersion"), "entitlementVersion"), + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"), + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"), + positiveDecimal(wire.get("tenantBillingSequence"), "tenantBillingSequence"), + bool(wire.get("gameplayAvailable"), "gameplayAvailable"), + bool(wire.get("allowPublicJoin"), "allowPublicJoin"), + bool(wire.get("allowNewGameplayBindings"), "allowNewGameplayBindings"), + bool(wire.get("allowNewInstanceStarts"), "allowNewInstanceStarts"), + quotas, + actualEventId, + streamKey, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException("Demo entitlement request ID is required"); + } + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map eventFields( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + UUID eventId, + String streamKey) { + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement event versions must be positive"); + } + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", SCHEMA_VERSION); + fields.put("eventType", EVENT_TYPE); + fields.put("eventId", eventId.toString()); + fields.put("requestId", request.requestId().toString()); + fields.put("requestDigest", request.requestDigest()); + fields.put("outboxStreamKey", streamKey); + fields.put("tenantId", request.canonicalTenantId().toString()); + fields.put("tenantBillingSequence", Long.toString(tenantBillingSequence)); + fields.put("tenantAuthorityGeneration", Long.toString(tenantAuthorityGeneration)); + fields.put("tenantAuthoritySourceVersion", Long.toString(tenantAuthoritySourceVersion)); + fields.put("entitlementVersion", Long.toString(entitlementVersion)); + fields.put("entitlementKind", "NON_PAID_DEMO"); + fields.put("status", "ACTIVE"); + fields.put("subscriptionStatus", null); + fields.put("paid", false); + fields.put("gameplayAvailable", request.gameplayAvailable()); + fields.put("allowPublicJoin", request.allowPublicJoin()); + fields.put("allowNewGameplayBindings", request.allowNewGameplayBindings()); + fields.put("allowNewInstanceStarts", request.allowNewInstanceStarts()); + fields.put("quotas", quotaFields(request.quotas())); + fields.put("sourceEvidence", sourceFields(source)); + return fields; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", source.schemaVersion()); + fields.put("targetNamespace", source.targetNamespace()); + fields.put("creationRequestId", source.creationRequestId().toString()); + fields.put("operationId", source.operationId().toString()); + fields.put("requestDigest", source.requestDigest()); + fields.put("canonicalTenantId", source.canonicalTenantId().toString()); + fields.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + fields.put("sourceGameTenantKey", source.sourceGameTenantKey()); + fields.put("provenanceKind", source.provenanceKind()); + fields.put("evidenceDigest", source.evidenceDigest()); + return fields; + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement event could not be canonicalized", exception); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " must be an object"); + } + for (Object key : raw.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " has invalid keys"); + } + } + return (Map) raw; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + String text = text(value, field); + UUID uuid; + try { + uuid = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is not a UUID", exception); + } + if (NIL_UUID.equals(uuid) || !uuid.toString().equals(text)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not canonical"); + } + return uuid; + } + + private static int integer(Object value, String field) { + if (!(value instanceof Number number)) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a JSON integer"); + } + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a positive JSON integer"); + } + try { + return Integer.parseInt(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is too large", exception); + } + } + + private static long positiveDecimal(Object value, String field) { + String encoded = decimalText(value, field, POSITIVE_DECIMAL, "positive"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static long nonnegativeDecimal(Object value, String field) { + String encoded = decimalText(value, field, NONNEGATIVE_DECIMAL, "non-negative"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static String decimalText( + Object value, String field, Pattern grammar, String description) { + if (!(value instanceof String encoded) || !grammar.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + + field + + " must be a canonical " + + description + + " decimal string"); + } + return encoded; + } + + private static Map quotaFields(DemoTenantEntitlementRequest.Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + private static boolean bool(Object value, String field) { + if (!(value instanceof Boolean result)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not boolean"); + } + return result; + } + + /** Exact closed event evidence stored in the Account entitlement outbox. */ + public record Event( + UUID requestId, + String requestDigest, + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + UUID eventId, + String outboxStreamKey, + String eventDigest, + byte[] payload) { + public Event { + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java new file mode 100644 index 0000000000..e6f8a3b16a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Explicit Account-owned non-paid demo entitlement mutation from a protected local fixture. */ +public record DemoTenantEntitlementRequest( + UUID requestId, + UUID canonicalTenantId, + UUID tenantCreationRequestId, + String tenantCreationRequestDigest, + Long expectedEntitlementVersion, + Long expectedTenantAuthorityGeneration, + Long expectedTenantAuthoritySourceVersion, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + Quotas quotas) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + public DemoTenantEntitlementRequest { + requireNonNil(requestId, "Demo entitlement request ID"); + requireNonNil(canonicalTenantId, "Canonical tenant UUID"); + requireNonNil(tenantCreationRequestId, "Fresh tenant creation request ID"); + if (tenantCreationRequestDigest == null + || !DIGEST.matcher(tenantCreationRequestDigest).matches()) { + throw new IllegalArgumentException("Fresh tenant creation request digest is invalid"); + } + boolean creating = expectedEntitlementVersion == null; + if (creating != (expectedTenantAuthorityGeneration == null) + || creating != (expectedTenantAuthoritySourceVersion == null)) { + throw new IllegalArgumentException( + "Demo entitlement create or update fence fields must be supplied together"); + } + if (!creating + && (expectedEntitlementVersion <= 0 + || expectedTenantAuthorityGeneration <= 0 + || expectedTenantAuthoritySourceVersion <= 0)) { + throw new IllegalArgumentException("Expected demo entitlement fences must be positive"); + } + Objects.requireNonNull(quotas, "Explicit demo entitlement quotas are required"); + } + + /** Stable normalized request digest; the request ID remains the operation identity. */ + public String requestDigest() { + Map normalized = new LinkedHashMap<>(); + normalized.put("schemaVersion", "account-demo-entitlement-request/v1"); + normalized.put("canonicalTenantId", canonicalTenantId.toString()); + normalized.put("tenantCreationRequestId", tenantCreationRequestId.toString()); + normalized.put("tenantCreationRequestDigest", tenantCreationRequestDigest); + normalized.put("expectedEntitlementVersion", decimal(expectedEntitlementVersion)); + normalized.put("expectedTenantAuthorityGeneration", decimal(expectedTenantAuthorityGeneration)); + normalized.put( + "expectedTenantAuthoritySourceVersion", decimal(expectedTenantAuthoritySourceVersion)); + normalized.put("entitlementKind", "NON_PAID_DEMO"); + normalized.put("subscriptionStatus", null); + normalized.put("paid", false); + normalized.put("status", "ACTIVE"); + normalized.put("gameplayAvailable", gameplayAvailable); + normalized.put("allowPublicJoin", allowPublicJoin); + normalized.put("allowNewGameplayBindings", allowNewGameplayBindings); + normalized.put("allowNewInstanceStarts", allowNewInstanceStarts); + normalized.put("quotas", quotaFields(quotas)); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(normalized)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement request digest could not be computed", exception); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static String decimal(Long value) { + return value == null ? null : Long.toString(value); + } + + private static Map quotaFields(Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + /** Quotas are explicit demo values and never copied from a paid plan or subscription. */ + public record Quotas( + long maxActiveSessions, long maxConcurrentGameInstances, long maxStorageBytes) { + public Quotas { + if (maxActiveSessions < 0 || maxConcurrentGameInstances < 0 || maxStorageBytes < 0) { + throw new IllegalArgumentException("Demo entitlement quotas cannot be negative"); + } + } + + public Map asMap() { + Map values = new LinkedHashMap<>(); + values.put("maxActiveSessions", maxActiveSessions); + values.put("maxConcurrentGameInstances", maxConcurrentGameInstances); + values.put("maxStorageBytes", maxStorageBytes); + return values; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java new file mode 100644 index 0000000000..d5de209ab2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; + +/** Exact committed demo entitlement and its current Account tenant-generation/outbox evidence. */ +public record DemoTenantEntitlementSnapshot( + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + String entitlementKind, + String status, + String subscriptionStatus, + boolean paid, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long tenantBillingSequence, + UUID eventId, + String eventDigest, + String snapshotIdentity, + String tenantAuthorityOutboxStreamKey, + long tenantAuthorityOutboxSequence, + UUID tenantAuthorityEventId, + String tenantAuthorityEventDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "NON_PAID_DEMO requires null subscriptionStatus; the compact record constructor implicitly stores that validated null.") + public DemoTenantEntitlementSnapshot { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + Objects.requireNonNull( + sourceEvidence, "Authenticated fresh tenant source evidence is required"); + if (!canonicalTenantId.equals(sourceEvidence.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement source evidence targets another tenant"); + } + if (!"NON_PAID_DEMO".equals(entitlementKind) + || !"ACTIVE".equals(status) + || subscriptionStatus != null + || paid) { + throw new IllegalArgumentException("Demo entitlement must remain explicitly non-paid"); + } + Objects.requireNonNull(quotas, "Demo entitlement quotas are required"); + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement currentness values must be positive"); + } + String expectedStream = AccountTenantEntitlementOutboxRepository.streamKey(canonicalTenantId); + if (!expectedStream.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement outbox scope differs from its tenant UUID"); + } + if (eventId == null || NIL_UUID.equals(eventId)) { + throw new IllegalArgumentException("Demo entitlement event ID is required"); + } + if (eventDigest == null || !EVENT_DIGEST.matcher(eventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement event digest is invalid"); + } + if (!eventDigest.equals(snapshotIdentity)) { + throw new IllegalArgumentException( + "Demo entitlement snapshot identity differs from its event"); + } + if (!TenantAuthorityEventV1Codec.streamKey(canonicalTenantId) + .equals(tenantAuthorityOutboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement authority stream differs from its tenant UUID"); + } + if (tenantAuthorityOutboxSequence <= 0L + || tenantAuthorityEventId == null + || NIL_UUID.equals(tenantAuthorityEventId) + || tenantAuthorityEventDigest == null + || !EVENT_DIGEST.matcher(tenantAuthorityEventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement authority event evidence is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java new file mode 100644 index 0000000000..2ec896e75a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java @@ -0,0 +1,427 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical event encoding for Account's independently sequenced tenant authority stream. + */ +public final class TenantAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-authority-event/v1"; + public static final String EVENT_TYPE = "TENANT_AUTHORITY_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "tenantId", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "outboxStreamKey", + "outboxSequence", + "tenantBillingReceipt", + "sourceEvidence", + "eventDigest"); + private static final Set BILLING_FIELDS = + Set.of("outboxStreamKey", "tenantBillingSequence", "eventId", "eventDigest"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private TenantAuthorityEventV1Codec() {} + + public static String streamKey(UUID tenantId) { + requireUuid(tenantId, "tenant UUID"); + return STREAM_PREFIX + tenantId; + } + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long outboxSequence, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + if (request == null || source == null || billingEvent == null) { + throw new IllegalArgumentException( + "Tenant authority request, source, and committed billing event are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || !request.requestId().equals(billingEvent.requestId()) + || !request.requestDigest().equals(billingEvent.requestDigest()) + || !request.canonicalTenantId().equals(billingEvent.canonicalTenantId())) { + throw new IllegalArgumentException( + "Tenant authority event differs from its exact source or billing request"); + } + requirePositive(tenantAuthorityGeneration, "tenant authority generation"); + requirePositive(tenantAuthoritySourceVersion, "tenant authority source version"); + requirePositive(outboxSequence, "authority outbox sequence"); + UUID eventId = eventId(request.requestId()); + String streamKey = streamKey(request.canonicalTenantId()); + Map preimage = + fields( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent, + source); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest(), + source, + digest, + payload); + } + + /** Parses and verifies the exact canonical Account authority event bytes. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Tenant authority event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Tenant authority event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Tenant authority event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + if (!claimedDigest.equals(digest(canonical(preimage))) + || !Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Tenant authority event digest or canonical bytes differ"); + } + String schemaVersion = text(wire.get("schemaVersion"), "schemaVersion"); + String eventType = text(wire.get("eventType"), "eventType"); + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID eventId = uuid(wire.get("eventId"), "eventId"); + String requestDigest = digestText(wire.get("requestDigest"), "requestDigest"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + long authorityGeneration = + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + long sourceVersion = + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"); + long sequence = positiveDecimal(wire.get("outboxSequence"), "outboxSequence"); + if (!SCHEMA_VERSION.equals(schemaVersion) + || !EVENT_TYPE.equals(eventType) + || !streamKey(tenantId).equals(streamKey) + || !eventId(requestId).equals(eventId)) { + throw new IllegalArgumentException("Tenant authority event scope or identity is invalid"); + } + + Map billing = object(wire.get("tenantBillingReceipt"), "tenantBillingReceipt"); + if (!billing.keySet().equals(BILLING_FIELDS)) { + throw new IllegalArgumentException("Tenant billing receipt fields are incomplete"); + } + String billingStream = text(billing.get("outboxStreamKey"), "billing outboxStreamKey"); + long billingSequence = + positiveDecimal(billing.get("tenantBillingSequence"), "tenantBillingSequence"); + UUID billingEventId = uuid(billing.get("eventId"), "billing eventId"); + String billingDigest = digestText(billing.get("eventDigest"), "billing eventDigest"); + if (!AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(billingStream)) { + throw new IllegalArgumentException("Tenant billing receipt has another tenant scope"); + } + if (!DemoTenantEntitlementEventV1Codec.eventId(requestId).equals(billingEventId)) { + throw new IllegalArgumentException("Tenant billing receipt has another request identity"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Tenant source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + digestText(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + digestText(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException("Tenant authority source evidence targets another tenant"); + } + return new Event( + requestId, + requestDigest, + tenantId, + authorityGeneration, + sourceVersion, + streamKey, + sequence, + eventId, + billingStream, + billingSequence, + billingEventId, + billingDigest, + source, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + requireUuid(requestId, "request ID"); + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map fields( + UUID requestId, + String requestDigest, + UUID tenantId, + long authorityGeneration, + long sourceVersion, + String streamKey, + long sequence, + UUID eventId, + DemoTenantEntitlementEventV1Codec.Event billingEvent, + FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", SCHEMA_VERSION); + values.put("eventType", EVENT_TYPE); + values.put("eventId", eventId.toString()); + values.put("requestId", requestId.toString()); + values.put("requestDigest", requestDigest); + values.put("tenantId", tenantId.toString()); + values.put("tenantAuthorityGeneration", Long.toString(authorityGeneration)); + values.put("tenantAuthoritySourceVersion", Long.toString(sourceVersion)); + values.put("outboxStreamKey", streamKey); + values.put("outboxSequence", Long.toString(sequence)); + Map billing = new LinkedHashMap<>(); + billing.put("outboxStreamKey", billingEvent.outboxStreamKey()); + billing.put("tenantBillingSequence", Long.toString(billingEvent.tenantBillingSequence())); + billing.put("eventId", billingEvent.eventId().toString()); + billing.put("eventDigest", billingEvent.eventDigest()); + values.put("tenantBillingReceipt", billing); + values.put("sourceEvidence", sourceFields(source)); + return values; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", source.schemaVersion()); + values.put("targetNamespace", source.targetNamespace()); + values.put("creationRequestId", source.creationRequestId().toString()); + values.put("operationId", source.operationId().toString()); + values.put("requestDigest", source.requestDigest()); + values.put("canonicalTenantId", source.canonicalTenantId().toString()); + values.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + values.put("sourceGameTenantKey", source.sourceGameTenantKey()); + values.put("provenanceKind", source.provenanceKind()); + values.put("evidenceDigest", source.evidenceDigest()); + return values; + } + + private static byte[] canonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Tenant authority event could not be canonicalized", exception); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not an object"); + } + Map result = new LinkedHashMap<>(); + raw.forEach( + (key, fieldValue) -> { + if (!(key instanceof String textKey)) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " has a bad key"); + } + result.put(textKey, fieldValue); + }); + return result; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank() || !text.equals(text.strip())) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static String digestText(Object value, String field) { + String text = text(value, field); + if (!DIGEST.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + try { + String text = text(value, field); + UUID uuid = UUID.fromString(text); + requireUuid(uuid, field); + if (!uuid.toString().equals(text)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not canonical"); + } + return uuid; + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is invalid", exception); + } + } + + private static int integer(Object value, String field) { + if (!(value instanceof Integer) || ((Integer) value) <= 0) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return (Integer) value; + } + + private static long positiveDecimal(Object value, String field) { + String text = text(value, field); + if (!POSITIVE_DECIMAL.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is out of range", exception); + } + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException("Tenant authority event " + field + " must be positive"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is required"); + } + } + + /** Exact authority event plus its independent tenant-billing and fresh-source linkage. */ + public record Event( + UUID requestId, + String requestDigest, + UUID tenantId, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long outboxSequence, + UUID eventId, + String tenantBillingStreamKey, + long tenantBillingSequence, + UUID tenantBillingEventId, + String tenantBillingEventDigest, + FreshTenantCreationEvidence sourceEvidence, + String eventDigest, + byte[] payload) { + public Event { + payload = payload == null ? null : payload.clone(); + requireUuid(requestId, "request ID"); + requireUuid(tenantId, "tenant UUID"); + requireUuid(eventId, "event ID"); + requireUuid(tenantBillingEventId, "billing event ID"); + if (requestDigest == null + || !DIGEST.matcher(requestDigest).matches() + || eventDigest == null + || !DIGEST.matcher(eventDigest).matches() + || tenantBillingEventDigest == null + || !DIGEST.matcher(tenantBillingEventDigest).matches() + || !streamKey(tenantId).equals(outboxStreamKey) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId) + .equals(tenantBillingStreamKey) + || tenantAuthorityGeneration <= 0L + || tenantAuthoritySourceVersion <= 0L + || outboxSequence <= 0L + || tenantBillingSequence <= 0L + || sourceEvidence == null + || !tenantId.equals(sourceEvidence.canonicalTenantId()) + || payload == null + || payload.length == 0) { + throw new IllegalArgumentException("Tenant authority event evidence is incomplete"); + } + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java new file mode 100644 index 0000000000..58872dedde --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java @@ -0,0 +1,340 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Reads only complete, current Account-owned evidence for non-admitting actor staging. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are private Account read collaborators.") +public class AccountActorStagingEligibilityRepository { + private final DSLContext dsl; + private final AccountRepository accounts; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository pairAuthority; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Spring must proxy this repository and all collaborators are required.") + public AccountActorStagingEligibilityRepository( + DSLContext dsl, + AccountRepository accounts, + FreshTenantIdentityAssociationRepository tenantIdentity, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairAuthority) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.tenantIdentity = Objects.requireNonNull(tenantIdentity); + this.memberships = Objects.requireNonNull(memberships); + this.pairAuthority = Objects.requireNonNull(pairAuthority); + } + + /** + * Reads identity, membership, pair authority, tenant provenance, checkpoint, and committed event + * inside the caller's single repeatable-read Account snapshot. Missing or contradictory evidence + * fails closed; this method never enrolls a pair or creates membership. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public CurrentSnapshot readCurrent(UUID accountUuid, UUID tenantUuid) { + requireReadOnlyOwnerTransaction(); + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + + Account account = + accounts + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); + if (account.getId() == null + || account.getId() <= 0L + || !accountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) + || account.getLifecycleState() == null) { + throw new IllegalStateException("Canonical Account identity or lifecycle is contradictory"); + } + + FreshTenantCreationEvidence tenantSource = + tenantIdentity + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Game Design tenant source is absent")); + if (!tenantUuid.equals(tenantSource.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(tenantSource.provenanceKind())) { + throw new IllegalStateException("Fresh Game Design tenant source is contradictory"); + } + + AccountTenantMembership membership = + memberships + .findFreshMembership(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Current positive Account membership is absent")); + PairAuthority pair = + pairAuthority + .readPositive(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Positive Account membership authority is absent")); + VerifiedTenantProvenance expectedProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantSource.operationId(), + tenantSource.evidenceDigest()); + requireMembershipMatchesSource( + accountUuid, tenantUuid, account, membership, pair, expectedProvenance); + + MembershipEventSnapshot committedEvent = readCurrentCommittedEvent(accountUuid, tenantUuid); + requireEventMatchesCurrentSources(accountUuid, tenantUuid, membership, pair, committedEvent); + + return new CurrentSnapshot( + accountUuid, + account.getAccountUuidProvenance(), + account.getLifecycleState().name(), + tenantUuid, + expectedProvenance.kind().name(), + expectedProvenance.sourceOperationId(), + expectedProvenance.digest(), + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getAuthorityProvenance(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + pair.eventSequence(), + parseCanonicalUuid(pair.eventId(), "membership event ID"), + pair.eventDigest(), + pair.lastTransitionInvalidated()); + } + + private MembershipEventSnapshot readCurrentCommittedEvent(UUID accountUuid, UUID tenantUuid) { + String streamKey = membershipStreamKey(accountUuid, tenantUuid); + Record row = + dsl.fetchOne( + "SELECT stream.last_sequence AS checkpoint_sequence, " + + "event.outbox_sequence AS event_sequence, event.request_id, event.event_id, " + + "event.event_digest, event.payload, " + + "(SELECT max(retained.outbox_sequence) " + + "FROM account_authority_outbox_events retained " + + "WHERE retained.outbox_stream_key = stream.outbox_stream_key) AS maximum_sequence " + + "FROM account_authority_outbox_streams stream " + + "JOIN account_authority_outbox_events event " + + "ON event.outbox_stream_key = stream.outbox_stream_key " + + "AND event.outbox_sequence = stream.last_sequence " + + "WHERE stream.outbox_stream_key = ? AND stream.last_sequence > 0", + streamKey); + if (row == null) { + throw new IllegalStateException("Current Account membership checkpoint or event is absent"); + } + + long checkpointSequence = requiredPositive(row, "checkpoint_sequence"); + long eventSequence = requiredPositive(row, "event_sequence"); + Long maximumSequence = row.get("maximum_sequence", Long.class); + String requestId = required(row, "request_id", String.class); + String eventId = required(row, "event_id", String.class); + String eventDigest = required(row, "event_digest", String.class); + byte[] payload = required(row, "payload", byte[].class); + if (checkpointSequence != eventSequence + || maximumSequence == null + || maximumSequence.longValue() != checkpointSequence) { + throw new IllegalStateException("Account membership checkpoint is not the stream head"); + } + + try { + AccountAuthorityOutboxRepository.Event event = + new AccountAuthorityOutboxRepository.Event( + streamKey, requestId, eventSequence, eventId, eventDigest, payload); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = + new AccountAuthorityOutboxRepository.Checkpoint( + streamKey, checkpointSequence, eventId, eventDigest); + return new MembershipEventSnapshot(event, checkpoint, verifyMembershipEvent(event)); + } catch (IllegalArgumentException invalidRecord) { + throw new IllegalStateException( + "Account membership event checkpoint is malformed", invalidRecord); + } + } + + private static MembershipEvent verifyMembershipEvent( + AccountAuthorityOutboxRepository.Event event) { + final MembershipEvent verified; + try { + verified = + MembershipAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException invalid) { + throw new IllegalStateException("Committed Account membership event is invalid", invalid); + } + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !event.requestId().equals(verified.requestId()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence())) { + throw new IllegalStateException( + "Committed Account membership event readback is contradictory"); + } + return verified; + } + + private static void requireEventMatchesCurrentSources( + UUID accountUuid, + UUID tenantUuid, + AccountTenantMembership membership, + PairAuthority pair, + MembershipEventSnapshot committed) { + AccountAuthorityOutboxRepository.Event event = committed.event(); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = committed.checkpoint(); + MembershipEvent decoded = committed.decoded(); + String tenantKey = tenantUuid.toString(); + if (!event.outboxStreamKey().equals(membershipStreamKey(accountUuid, tenantUuid)) + || !checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != pair.eventSequence() + || !checkpoint.sourceEventId().equals(pair.eventId()) + || !checkpoint.sourceEventDigest().equals(pair.eventDigest()) + || event.outboxSequence() != pair.eventSequence() + || !event.eventId().equals(pair.eventId()) + || !event.eventDigest().equals(pair.eventDigest()) + || !accountUuid.toString().equals(decoded.accountId()) + || !tenantKey.equals(decoded.tenantId()) + || !decoded.sourceScope().equals("membership/" + accountUuid + "/" + tenantUuid) + || !membership.getLifecycleState().equals(decoded.membershipLifecycleState()) + || !Long.toString(membership.getMembershipVersion()) + .equals(decoded.membershipVersion().get(tenantKey)) + || !Long.toString(membership.getMembershipAuthorityGeneration()) + .equals(decoded.membershipAuthorityGeneration()) + || membership.isGameplayAdmissionAllowed() != decoded.gameplayAdmissionAllowed() + || pair.lastTransitionInvalidated() != decoded.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Committed Account membership event differs from the current membership and pair state"); + } + } + + private static void requireMembershipMatchesSource( + UUID accountUuid, + UUID tenantUuid, + Account account, + AccountTenantMembership membership, + PairAuthority pair, + VerifiedTenantProvenance expectedProvenance) { + if (membership.getAccount() == null + || !Objects.equals(account.getId(), membership.getAccount().getId()) + || !accountUuid.equals(membership.getAccount().getAccountUuid()) + || membership.getTenantId() != null + || !tenantUuid.equals(membership.getTenantUuid()) + || !expectedProvenance.equals(pair.provenance()) + || !expectedProvenance.kind().name().equals(membership.getTenantProvenanceKind()) + || !expectedProvenance.sourceOperationId().equals(membership.getTenantSourceOperationId()) + || !expectedProvenance.digest().equals(membership.getTenantProvenanceDigest()) + || !pair.membershipExists() + || pair.eventSequence() <= 0L + || pair.membershipVersion() != membership.getMembershipVersion() + || pair.membershipAuthorityGeneration() != membership.getMembershipAuthorityGeneration() + || membership.getMembershipVersion() <= 0L + || membership.getMembershipAuthorityGeneration() <= 0L + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance()) + || (!"ACTIVE".equals(membership.getLifecycleState()) + && !"INACTIVE".equals(membership.getLifecycleState()))) { + throw new IllegalStateException( + "Canonical Account membership or its current authority source is contradictory"); + } + } + + private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private static long requiredPositive(Record row, String field) { + Long value = required(row, field, Long.class); + if (value <= 0L) { + throw new IllegalStateException("Account membership event source lacks positive " + field); + } + return value; + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new IllegalStateException("Account membership event source lacks " + field); + } + return value; + } + + private static UUID parseCanonicalUuid(String value, String label) { + if (value == null) { + throw new IllegalStateException("Account membership source lacks " + label); + } + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException("not canonical"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account membership source has invalid " + label, invalid); + } + } + + private static void requireCanonicalUuid(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical nonnil UUID"); + } + } + + private static void requireReadOnlyOwnerTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || isolation == null + || isolation != TransactionDefinition.ISOLATION_REPEATABLE_READ) { + throw new IllegalStateException( + "Actor-staging eligibility reads require a repeatable-read, read-only Account snapshot"); + } + } + + private record MembershipEventSnapshot( + AccountAuthorityOutboxRepository.Event event, + AccountAuthorityOutboxRepository.Checkpoint checkpoint, + MembershipEvent decoded) {} + + /** Exact source values sealed into the cross-service evidence response. */ + public record CurrentSnapshot( + UUID accountUuid, + AccountIdentityProvenance accountUuidProvenance, + String accountLifecycleState, + UUID tenantUuid, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java new file mode 100644 index 0000000000..77d1cabbaf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -0,0 +1,546 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException.Code; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account's exact-UUID demo entitlement source, commit, lookup, and currentness fence. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are private transaction collaborators.") +public class AccountDemoTenantEntitlementRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final FreshTenantIdentityAssociationRepository tenantIdentityRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountTenantEntitlementOutboxRepository outboxRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") + public AccountDemoTenantEntitlementRepository( + DSLContext dsl, + FreshTenantIdentityAssociationRepository tenantIdentityRepository, + AccountAuthorityGenerationRepository authorityGenerationRepository, + AccountTenantEntitlementOutboxRepository outboxRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEvents) { + this.dsl = Objects.requireNonNull(dsl); + this.tenantIdentityRepository = Objects.requireNonNull(tenantIdentityRepository); + this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); + this.outboxRepository = Objects.requireNonNull(outboxRepository); + this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents); + } + + /** Commits one protected-fixture mutation with source readback, shared generation, and outbox. */ + @Transactional(propagation = Propagation.MANDATORY) + public DemoTenantEntitlementSnapshot provision( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + requireTransaction(); + Objects.requireNonNull(request, "Demo entitlement request is required"); + requireExactSource(request, authenticatedSource); + FreshTenantCreationEvidence currentSource = + tenantIdentityRepository + .read(request.canonicalTenantId()) + .orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Exact fresh Game Design source evidence is absent at Account commit")); + if (!authenticatedSource.equals(currentSource)) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Authenticated source evidence differs from exact Account UUID readback at commit"); + } + + int reserved = + dsl.execute( + "INSERT INTO account_demo_tenant_entitlement_operations (request_id, tenant_uuid, " + + "request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING') ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + request.canonicalTenantId(), + request.requestDigest(), + authenticatedSource.creationRequestId(), + authenticatedSource.requestDigest(), + authenticatedSource.operationId(), + authenticatedSource.evidenceDigest()); + if (reserved == 0) { + return replay(request, authenticatedSource); + } + if (reserved != 1) { + throw new IllegalStateException("Demo entitlement request reservation was ambiguous"); + } + + ScopeState oldAuthority = + authorityGenerationRepository.read(AuthorityScope.tenant(request.canonicalTenantId())); + Record oldEntitlement = readCurrentRow(request.canonicalTenantId(), true); + if (oldEntitlement == null) { + tenantAuthorityEvents.establishFirstEventSource( + request.canonicalTenantId(), request.requestId(), authenticatedSource, oldAuthority); + } + long nextEntitlementVersion; + if (oldEntitlement == null) { + if (request.expectedEntitlementVersion() != null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_VERSION_CONFLICT, + "Demo entitlement create request supplied an update fence"); + } + nextEntitlementVersion = 1L; + } else { + if (request.expectedEntitlementVersion() == null + || request.expectedEntitlementVersion() != value(oldEntitlement, "entitlement_version") + || request.expectedTenantAuthorityGeneration() != oldAuthority.generation() + || request.expectedTenantAuthoritySourceVersion() != oldAuthority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Demo entitlement update does not match the exact current entitlement and tenant authority"); + } + nextEntitlementVersion = increment(value(oldEntitlement, "entitlement_version")); + } + ScopeState nextAuthority = authorityGenerationRepository.advance(oldAuthority, null); + final long committedEntitlementVersion = nextEntitlementVersion; + Event committedEvent = + outboxRepository.append( + request.canonicalTenantId(), + request.requestId(), + sequence -> + DemoTenantEntitlementEventV1Codec.seal( + request, + authenticatedSource, + committedEntitlementVersion, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence)); + + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.append(request, authenticatedSource, nextAuthority, committedEvent); + + writeCurrent( + request, authenticatedSource, committedEvent, authorityEvent, oldEntitlement == null); + int committed = + dsl.execute( + "UPDATE account_demo_tenant_entitlement_operations SET status = 'COMMITTED', " + + "tenant_billing_sequence = ?, event_id = ?, event_digest = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_authority_outbox_stream_key = ?, " + + "tenant_authority_outbox_sequence = ?, tenant_authority_event_id = ?, " + + "tenant_authority_event_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status = 'PENDING'", + committedEvent.tenantBillingSequence(), + committedEvent.eventId(), + committedEvent.eventDigest(), + committedEvent.entitlementVersion(), + committedEvent.tenantAuthorityGeneration(), + committedEvent.tenantAuthoritySourceVersion(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.requestId()); + if (committed != 1) { + throw new IllegalStateException("Demo entitlement operation receipt was not committed"); + } + return snapshot(committedEvent, authorityEvent); + } + + /** Reads one exact current snapshot and denies stale or incomplete Account/source state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { + requireTenantUuid(canonicalTenantId); + Optional evidence = + tenantIdentityRepository.read(canonicalTenantId); + FreshTenantCreationEvidence source = + evidence.orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "No exact fresh Game Design source evidence exists for this tenant UUID")); + ScopeState authority = + authorityGenerationRepository.read(AuthorityScope.tenant(canonicalTenantId)); + Record row = readCurrentRow(canonicalTenantId, false); + if (row == null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "No Account demo entitlement exists for this tenant UUID"); + } + CurrentEvents current = currentEvents(row, source, authority); + return snapshot(current.billingEvent(), current.authorityEvent()); + } + + /** Re-reads all source, generation, version, and outbox evidence at the final admission fence. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DemoTenantEntitlementSnapshot revalidate(DemoTenantEntitlementSnapshot evaluated) { + Objects.requireNonNull(evaluated, "Complete evaluated entitlement evidence is required"); + DemoTenantEntitlementSnapshot current = readCurrent(evaluated.canonicalTenantId()); + if (!current.equals(evaluated)) { + throw new DemoTenantEntitlementException( + Code.STALE_ADMISSION_EVIDENCE, + "Account demo entitlement changed after its complete evaluation snapshot"); + } + return current; + } + + private DemoTenantEntitlementSnapshot replay( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, " + + "source_request_digest, source_operation_id, source_evidence_digest, status, " + + "tenant_billing_sequence, event_id, event_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest " + + "FROM account_demo_tenant_entitlement_operations WHERE request_id = ? FOR UPDATE", + request.requestId()); + if (operation == null + || !request.canonicalTenantId().equals(get(operation, "tenant_uuid", UUID.class)) + || !request.requestDigest().equals(get(operation, "request_digest", String.class)) + || !authenticatedSource + .creationRequestId() + .equals(get(operation, "source_creation_request_id", UUID.class)) + || !authenticatedSource + .requestDigest() + .equals(get(operation, "source_request_digest", String.class)) + || !authenticatedSource + .operationId() + .equals(get(operation, "source_operation_id", UUID.class)) + || !authenticatedSource + .evidenceDigest() + .equals(get(operation, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.IDEMPOTENCY_CONFLICT, + "Demo entitlement request ID was reused for a different tenant or payload"); + } + if (!"COMMITTED".equals(get(operation, "status", String.class))) { + throw new IllegalStateException("Committed Account contains an unfinished demo operation"); + } + long sequence = value(operation, "tenant_billing_sequence"); + Event event = + outboxRepository + .readEvent(request.canonicalTenantId(), sequence) + .orElseThrow( + () -> + new IllegalStateException("Committed demo entitlement operation has no event")); + if (!request.requestId().equals(event.requestId()) + || !request.requestDigest().equals(event.requestDigest()) + || !event.eventId().equals(get(operation, "event_id", UUID.class)) + || !event.eventDigest().equals(get(operation, "event_digest", String.class)) + || !authenticatedSource.equals(event.sourceEvidence())) { + throw new IllegalStateException("Committed demo entitlement receipt differs from its event"); + } + var authorityEvent = + tenantAuthorityEvents.readCommittedReceipt( + request.canonicalTenantId(), + request.requestId(), + request.requestDigest(), + authenticatedSource, + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + value(operation, "tenant_authority_outbox_sequence"), + get(operation, "tenant_authority_event_id", String.class), + get(operation, "tenant_authority_event_digest", String.class)); + if (!authorityEvent + .outboxStreamKey() + .equals(get(operation, "tenant_authority_outbox_stream_key", String.class)) + || authorityEvent.tenantAuthorityGeneration() != event.tenantAuthorityGeneration() + || authorityEvent.tenantAuthoritySourceVersion() != event.tenantAuthoritySourceVersion()) { + throw new IllegalStateException( + "Committed demo entitlement receipt differs from its tenant authority event"); + } + return snapshot(event, authorityEvent); + } + + private CurrentEvents currentEvents( + Record row, FreshTenantCreationEvidence source, ScopeState authority) { + long storedGeneration = value(row, "tenant_authority_generation"); + long storedSourceVersion = value(row, "tenant_authority_source_version"); + if (storedGeneration != authority.generation() + || storedSourceVersion != authority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Stored demo entitlement is stale against Account's shared tenant authority generation"); + } + if (source.schemaVersion() != get(row, "source_schema_version", Integer.class) + || !source.targetNamespace().equals(get(row, "source_target_namespace", String.class)) + || !source.creationRequestId().equals(get(row, "source_creation_request_id", UUID.class)) + || !source.operationId().equals(get(row, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(get(row, "source_request_digest", String.class)) + || source.sourceGameRowId() != value(row, "source_game_row_id") + || !source.sourceGameTenantKey().equals(get(row, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(get(row, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(get(row, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Stored demo entitlement source tuple differs from current authenticated Account source evidence"); + } + long sequence = value(row, "tenant_billing_sequence"); + var checkpoint = + outboxRepository + .readCheckpoint(source.canonicalTenantId()) + .orElseThrow( + () -> + new IllegalStateException("Current demo entitlement has no outbox checkpoint")); + if (checkpoint.sequence() != sequence + || !checkpoint.eventId().equals(get(row, "event_id", UUID.class)) + || !checkpoint.eventDigest().equals(get(row, "event_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Current demo entitlement does not match the exact tenant entitlement outbox head"); + } + Event event = + outboxRepository + .readEvent(source.canonicalTenantId(), sequence) + .orElseThrow( + () -> new IllegalStateException("Current demo entitlement event is absent")); + if (!source.equals(event.sourceEvidence()) + || event.entitlementVersion() != value(row, "entitlement_version") + || event.tenantAuthorityGeneration() != storedGeneration + || event.tenantAuthoritySourceVersion() != storedSourceVersion + || !event.requestId().equals(get(row, "last_request_id", UUID.class)) + || !event.requestDigest().equals(get(row, "last_request_digest", String.class)) + || !event.eventId().equals(get(row, "event_id", UUID.class)) + || !event.eventDigest().equals(get(row, "event_digest", String.class)) + || event.gameplayAvailable() != get(row, "gameplay_available", Boolean.class) + || event.allowPublicJoin() != get(row, "allow_public_join", Boolean.class) + || event.allowNewGameplayBindings() + != get(row, "allow_new_gameplay_bindings", Boolean.class) + || event.allowNewInstanceStarts() != get(row, "allow_new_instance_starts", Boolean.class) + || !event + .quotas() + .equals( + new DemoTenantEntitlementRequest.Quotas( + value(row, "max_active_sessions"), + value(row, "max_concurrent_game_instances"), + value(row, "max_storage_bytes")))) { + throw new IllegalStateException("Current demo entitlement projection differs from its event"); + } + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.readCurrentCheckpoint( + source.canonicalTenantId(), + source, + authority, + event.requestId(), + event.requestDigest(), + sequence, + event.eventId(), + event.eventDigest()); + if (authorityEvent.tenantAuthorityGeneration() != storedGeneration + || authorityEvent.tenantAuthoritySourceVersion() != storedSourceVersion) { + throw new IllegalStateException( + "Current tenant authority event differs from Account's actual generation"); + } + return new CurrentEvents(event, authorityEvent); + } + + private void writeCurrent( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + Event event, + TenantAuthorityEventV1Codec.Event authorityEvent, + boolean insert) { + String sql = + insert + ? "INSERT INTO account_demo_tenant_entitlements (tenant_uuid, source_schema_version, " + + "source_target_namespace, source_creation_request_id, source_operation_id, " + + "source_request_digest, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, entitlement_kind, status, " + + "subscription_status, paid, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NON_PAID_DEMO', 'ACTIVE', NULL, FALSE, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + : "UPDATE account_demo_tenant_entitlements SET gameplay_available = ?, " + + "allow_public_join = ?, allow_new_gameplay_bindings = ?, allow_new_instance_starts = ?, " + + "max_active_sessions = ?, max_concurrent_game_instances = ?, max_storage_bytes = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_billing_sequence = ?, event_id = ?, " + + "event_digest = ?, last_request_id = ?, last_request_digest = ?, " + + "tenant_authority_outbox_stream_key = ?, tenant_authority_outbox_sequence = ?, " + + "tenant_authority_event_id = ?, tenant_authority_event_digest = ? " + + "WHERE tenant_uuid = ?"; + Object[] values = + insert + ? new Object[] { + request.canonicalTenantId(), + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest() + } + : new Object[] { + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.canonicalTenantId() + }; + int changed = dsl.execute(sql, values); + if (changed != 1) { + throw new IllegalStateException( + "Demo entitlement current state was not committed exactly once"); + } + } + + private Record readCurrentRow(UUID tenantId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_version, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, tenant_authority_generation, " + + "tenant_authority_source_version, tenant_billing_sequence, event_id, event_digest, " + + "last_request_id, last_request_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlements " + + "WHERE tenant_uuid = ?" + + (forUpdate ? " FOR UPDATE" : " FOR SHARE"), + tenantId); + } + + private static DemoTenantEntitlementSnapshot snapshot( + Event event, TenantAuthorityEventV1Codec.Event authorityEvent) { + return new DemoTenantEntitlementSnapshot( + event.canonicalTenantId(), + event.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + event.gameplayAvailable(), + event.allowPublicJoin(), + event.allowNewGameplayBindings(), + event.allowNewInstanceStarts(), + event.quotas(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.outboxStreamKey(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + event.eventDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId(), + authorityEvent.eventDigest()); + } + + private record CurrentEvents( + Event billingEvent, TenantAuthorityEventV1Codec.Event authorityEvent) {} + + private static void requireExactSource( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence source) { + if (source == null + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Only exact authenticated fresh Game Design tenant creation evidence can receive a demo entitlement"); + } + } + + private static void requireTenantUuid(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "Exact non-nil canonical tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account demo entitlement operation requires one owner transaction"); + } + } + + private static long value(Record row, String column) { + Long value = row.get(column, Long.class); + if (value == null || value < 0) { + throw new IllegalStateException("Account demo entitlement " + column + " is malformed"); + } + return value; + } + + private static long increment(long current) { + try { + return Math.addExact(current, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account demo entitlement version is exhausted", overflow); + } + } + + private static T get(Record row, String column, Class type) { + T result = row.get(column, type); + if (result == null) { + throw new IllegalStateException("Account demo entitlement " + column + " is absent"); + } + return result; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java new file mode 100644 index 0000000000..60655921ca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -0,0 +1,580 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Typed tenant-authority source, outbox, receipt, and current-checkpoint readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and DSLContext are private transaction collaborators.") +public class AccountTenantAuthorityEventRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final AccountAuthorityOutboxRepository authorityOutbox; + private final AccountTenantEntitlementOutboxRepository billingOutbox; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountAuthorityGenerationRepository generations; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") + public AccountTenantAuthorityEventRepository( + DSLContext dsl, + AccountAuthorityOutboxRepository authorityOutbox, + AccountTenantEntitlementOutboxRepository billingOutbox, + FreshTenantIdentityAssociationRepository tenantIdentity, + AccountAuthorityGenerationRepository generations) { + this.dsl = Objects.requireNonNull(dsl); + this.authorityOutbox = Objects.requireNonNull(authorityOutbox); + this.billingOutbox = Objects.requireNonNull(billingOutbox); + this.tenantIdentity = Objects.requireNonNull(tenantIdentity); + this.generations = Objects.requireNonNull(generations); + } + + /** Establishes sequence zero only from the same Account transaction that enrolled the tenant. */ + @Transactional(propagation = Propagation.MANDATORY) + public void establishFirstEventSource( + UUID tenantId, UUID requestId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + if (authority.generation() != 1L || authority.sourceVersion() != 1L) { + throw new IllegalStateException( + "Tenant authority has advanced without canonical source-event evidence"); + } + + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record existingSource = + dsl.fetchOne( + "SELECT last_outbox_sequence FROM account_tenant_authority_source_records " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (existingSource != null) { + throw new IllegalStateException( + "Tenant authority source already exists without its current entitlement row"); + } + + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (stream != null) { + throw new IllegalStateException( + "Tenant authority stream exists without Account source initialization proof"); + } + + Record sourceInitialization = + dsl.fetchOne( + "SELECT fresh.authority_source_transaction_id, generation.created_transaction_id, " + + "generation.generation, generation.source_version " + + "FROM account_fresh_tenant_identity_associations fresh " + + "JOIN account_canonical_tenant_identity_claims claim " + + "ON claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "AND claim.identity_kind = 'FRESH_GAME_DESIGN' " + + "AND claim.source_operation_id = fresh.operation_id " + + "AND claim.source_creation_request_id = fresh.creation_request_id " + + "AND claim.source_request_digest = fresh.request_digest " + + "AND claim.source_game_row_id = fresh.source_game_row_id " + + "AND claim.source_game_tenant_key = fresh.source_game_tenant_key " + + "AND claim.source_provenance_kind = fresh.provenance_kind " + + "AND claim.source_evidence_digest = fresh.evidence_digest " + + "JOIN account_authority_generations generation " + + "ON generation.scope_kind = 'TENANT' " + + "AND generation.tenant_uuid = fresh.canonical_tenant_id " + + "WHERE fresh.canonical_tenant_id = ?", + tenantId); + if (sourceInitialization == null + || sourceInitialization.get("authority_source_transaction_id", Long.class) == null + || !Objects.equals( + sourceInitialization.get("authority_source_transaction_id", Long.class), + sourceInitialization.get("created_transaction_id", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("generation", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("source_version", Long.class))) { + throw new IllegalStateException( + "Fresh tenant source and Account generation lack one owner initialization proof"); + } + + Record billingStream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + Record priorOperation = + dsl.fetchOne( + "SELECT request_id FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ? AND request_id <> ? LIMIT 1", + tenantId, + requestId); + if (billingStream != null || priorOperation != null) { + throw new IllegalStateException( + "Tenant has retained billing history without canonical authority source evidence"); + } + + int streamInserted = + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (outbox_stream_key) DO NOTHING", + streamKey); + if (streamInserted != 1) { + throw new IllegalStateException( + "Tenant authority stream changed before Account source enrollment"); + } + long initializationTransactionId = + sourceInitialization.get("created_transaction_id", Long.class); + int sourceInserted = + dsl.execute( + "INSERT INTO account_tenant_authority_source_records (outbox_stream_key, tenant_uuid, " + + "initialization_transaction_id, baseline_generation, baseline_source_version, " + + "current_generation, current_source_version, last_outbox_sequence) " + + "VALUES (?, ?, ?, 1, 1, 1, 1, 0)", + streamKey, + tenantId, + initializationTransactionId); + if (sourceInserted != 1) { + throw new IllegalStateException("Tenant authority source baseline was not enrolled"); + } + } + + /** Appends one tenant-scoped event after the owner has advanced the exact generation row. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + ScopeState nextAuthority, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + requireTransaction(); + if (request == null || billingEvent == null) { + throw new IllegalArgumentException("Tenant authority request and billing event are required"); + } + requireExactTenant(request.canonicalTenantId(), source, nextAuthority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(request.canonicalTenantId()); + Record sourceHead = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (sourceHead == null || nonnegative(sourceHead, "last_outbox_sequence") < 0L) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + if (increment(positive(sourceHead, "current_generation"), "generation") + != nextAuthority.generation() + || increment(positive(sourceHead, "current_source_version"), "source version") + != nextAuthority.sourceVersion()) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + AccountAuthorityOutboxRepository.Event committed = + authorityOutbox.append( + streamKey, + request.requestId().toString(), + sequence -> + evidence( + TenantAuthorityEventV1Codec.seal( + request, + source, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence, + billingEvent))); + TenantAuthorityEventV1Codec.Event typed = + TenantAuthorityEventV1Codec.verify(committed.payload()); + if (!committed.outboxStreamKey().equals(streamKey) + || !committed.requestId().equals(request.requestId().toString()) + || typed.outboxSequence() != committed.outboxSequence() + || !typed.eventId().toString().equals(committed.eventId()) + || !typed.eventDigest().equals(committed.eventDigest()) + || !request.requestId().equals(typed.requestId()) + || !request.requestDigest().equals(typed.requestDigest()) + || !source.equals(typed.sourceEvidence()) + || typed.tenantAuthorityGeneration() != nextAuthority.generation() + || typed.tenantAuthoritySourceVersion() != nextAuthority.sourceVersion() + || typed.tenantBillingSequence() != billingEvent.tenantBillingSequence() + || !typed.tenantBillingEventId().equals(billingEvent.eventId()) + || !typed.tenantBillingEventDigest().equals(billingEvent.eventDigest())) { + throw new IllegalStateException( + "Committed tenant authority outbox event differs from its exact Account source"); + } + int updated = + dsl.execute( + "UPDATE account_tenant_authority_source_records SET current_generation = ?, " + + "current_source_version = ?, last_outbox_sequence = ?, last_request_id = ?, " + + "last_request_digest = ?, last_event_id = ?, last_event_digest = ?, " + + "tenant_billing_sequence = ?, tenant_billing_event_id = ?, " + + "tenant_billing_event_digest = ? WHERE outbox_stream_key = ? " + + "AND current_generation = ? AND current_source_version = ? " + + "AND last_outbox_sequence = ?", + typed.tenantAuthorityGeneration(), + typed.tenantAuthoritySourceVersion(), + typed.outboxSequence(), + typed.requestId(), + typed.requestDigest(), + typed.eventId().toString(), + typed.eventDigest(), + typed.tenantBillingSequence(), + typed.tenantBillingEventId(), + typed.tenantBillingEventDigest(), + streamKey, + typed.tenantAuthorityGeneration() - 1L, + typed.tenantAuthoritySourceVersion() - 1L, + typed.outboxSequence() - 1L); + if (updated != 1) { + throw new IllegalStateException("Tenant authority source checkpoint was not advanced once"); + } + return typed; + } + + /** + * Verifies the exact event and owning committed receipt, without requiring it to remain latest. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCommittedReceipt( + UUID tenantId, + UUID requestId, + String requestDigest, + FreshTenantCreationEvidence source, + long billingSequence, + UUID billingEventId, + String billingEventDigest, + long authoritySequence, + String authorityEventId, + String authorityEventDigest) { + requireTransaction(); + requireTenant(tenantId); + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status, tenant_billing_sequence, " + + "event_id, event_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlement_operations " + + "WHERE request_id = ?", + requestId); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + if (operation == null + || !tenantId.equals(operation.get("tenant_uuid", UUID.class)) + || !requestDigest.equals(operation.get("request_digest", String.class)) + || !"COMMITTED".equals(operation.get("status", String.class)) + || !source + .creationRequestId() + .equals(operation.get("source_creation_request_id", UUID.class)) + || !source.requestDigest().equals(operation.get("source_request_digest", String.class)) + || !source.operationId().equals(operation.get("source_operation_id", UUID.class)) + || !source.evidenceDigest().equals(operation.get("source_evidence_digest", String.class)) + || billingSequence != positive(operation, "tenant_billing_sequence") + || !billingEventId.equals(operation.get("event_id", UUID.class)) + || !billingEventDigest.equals(operation.get("event_digest", String.class)) + || !streamKey.equals(operation.get("tenant_authority_outbox_stream_key", String.class)) + || authoritySequence != positive(operation, "tenant_authority_outbox_sequence") + || !authorityEventId.equals(operation.get("tenant_authority_event_id", String.class)) + || !authorityEventDigest.equals( + operation.get("tenant_authority_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority readback has no exact owning committed entitlement receipt"); + } + AccountAuthorityOutboxRepository.Event stored = + authorityOutbox + .findEvent(streamKey, authoritySequence) + .orElseThrow( + () -> new IllegalStateException("Tenant authority event is absent at its receipt")); + Event event = TenantAuthorityEventV1Codec.verify(stored.payload()); + if (!stored.eventId().equals(event.eventId().toString()) + || !stored.eventDigest().equals(event.eventDigest()) + || !stored.requestId().equals(requestId.toString()) + || !event.requestDigest().equals(requestDigest) + || !event.tenantId().equals(tenantId) + || !source.equals(event.sourceEvidence()) + || event.tenantBillingSequence() != billingSequence + || !event.tenantBillingEventId().equals(billingEventId) + || !event.tenantBillingEventDigest().equals(billingEventDigest)) { + throw new IllegalStateException( + "Tenant authority event differs from its exact entitlement receipt or source"); + } + DemoTenantEntitlementEventV1Codec.Event billing = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow( + () -> new IllegalStateException("Tenant billing event is absent at its receipt")); + if (!billing.eventId().equals(billingEventId) + || !billing.eventDigest().equals(billingEventDigest) + || !requestId.equals(billing.requestId()) + || !requestDigest.equals(billing.requestDigest()) + || !source.equals(billing.sourceEvidence())) { + throw new IllegalStateException( + "Tenant authority event does not link to the exact original billing event"); + } + return event; + } + + /** Verifies that a current Account generation is represented by the exact latest source event. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentCheckpoint( + UUID tenantId, + FreshTenantCreationEvidence source, + ScopeState authority, + UUID requestId, + String requestDigest, + long billingSequence, + UUID billingEventId, + String billingEventDigest) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record head = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence, " + + "last_event_id, last_event_digest, last_request_id, last_request_digest, " + + "tenant_billing_sequence, tenant_billing_event_id, tenant_billing_event_digest " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ?", + streamKey); + if (head == null + || positive(head, "current_generation") != authority.generation() + || positive(head, "current_source_version") != authority.sourceVersion() + || !requestId.equals(head.get("last_request_id", UUID.class)) + || !requestDigest.equals(head.get("last_request_digest", String.class)) + || billingSequence != positive(head, "tenant_billing_sequence") + || !billingEventId.equals(head.get("tenant_billing_event_id", UUID.class)) + || !billingEventDigest.equals(head.get("tenant_billing_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority source checkpoint is absent, stale, or differs from Account current state"); + } + long sequence = positive(head, "last_outbox_sequence"); + String eventId = requiredText(head, "last_event_id"); + String eventDigest = requiredText(head, "last_event_digest"); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = + authorityOutbox + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Tenant authority outbox checkpoint is absent")); + if (checkpoint.outboxSequence() != sequence + || !checkpoint.sourceEventId().equals(eventId) + || !checkpoint.sourceEventDigest().equals(eventDigest)) { + throw new IllegalStateException( + "Tenant authority source checkpoint differs from its canonical outbox head"); + } + return readCommittedReceipt( + tenantId, + requestId, + requestDigest, + source, + billingSequence, + billingEventId, + billingEventDigest, + sequence, + eventId, + eventDigest); + } + + /** Resolves current Account owner state itself; callers cannot supply a receipt or checkpoint. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentByTenant(UUID tenantId) { + requireTransaction(); + requireTenant(tenantId); + Record freshIdentity = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ? FOR SHARE", + tenantId); + if (freshIdentity == null + || !tenantId.equals(freshIdentity.get("canonical_tenant_id", UUID.class))) { + throw new IllegalStateException( + "Exact fresh Account tenant source association is unavailable"); + } + FreshTenantCreationEvidence source = + tenantIdentity + .read(tenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Exact fresh Account tenant source evidence is unavailable")); + ScopeState authority = + generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); + Record current = + dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_kind, status, subscription_status, paid, gameplay_available, " + + "allow_public_join, allow_new_gameplay_bindings, allow_new_instance_starts, " + + "max_active_sessions, max_concurrent_game_instances, max_storage_bytes, " + + "entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest " + + "FROM account_demo_tenant_entitlements WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (current == null + || !source.equals(sourceFromCurrent(tenantId, current)) + || positive(current, "tenant_authority_generation") != authority.generation() + || positive(current, "tenant_authority_source_version") != authority.sourceVersion() + || !TenantAuthorityEventV1Codec.streamKey(tenantId) + .equals(current.get("tenant_authority_outbox_stream_key", String.class))) { + throw new IllegalStateException( + "Account current tenant entitlement lacks matching fresh source and authority generation"); + } + long billingSequence = positive(current, "tenant_billing_sequence"); + UUID billingEventId = requiredUuid(current, "event_id"); + String billingEventDigest = requiredText(current, "event_digest"); + UUID requestId = requiredUuid(current, "last_request_id"); + String requestDigest = requiredText(current, "last_request_digest"); + long authoritySequence = positive(current, "tenant_authority_outbox_sequence"); + String authorityEventId = requiredText(current, "tenant_authority_event_id"); + String authorityEventDigest = requiredText(current, "tenant_authority_event_digest"); + Event event = + readCurrentCheckpoint( + tenantId, + source, + authority, + requestId, + requestDigest, + billingSequence, + billingEventId, + billingEventDigest); + if (event.outboxSequence() != authoritySequence + || !event.eventId().toString().equals(authorityEventId) + || !event.eventDigest().equals(authorityEventDigest) + || event.tenantAuthorityGeneration() != authority.generation() + || event.tenantAuthoritySourceVersion() != authority.sourceVersion()) { + throw new IllegalStateException( + "Account current tenant row differs from its exact typed authority event"); + } + DemoTenantEntitlementEventV1Codec.Event billingEvent = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow(() -> new IllegalStateException("Current tenant billing event is absent")); + if (!billingEvent.eventId().equals(billingEventId) + || !billingEvent.eventDigest().equals(billingEventDigest) + || !billingEvent.requestId().equals(requestId) + || !billingEvent.requestDigest().equals(requestDigest) + || !source.equals(billingEvent.sourceEvidence()) + || billingEvent.tenantAuthorityGeneration() != authority.generation() + || billingEvent.tenantAuthoritySourceVersion() != authority.sourceVersion() + || !"NON_PAID_DEMO".equals(current.get("entitlement_kind", String.class)) + || !"ACTIVE".equals(current.get("status", String.class)) + || current.get("subscription_status", String.class) != null + || !Boolean.FALSE.equals(current.get("paid", Boolean.class)) + || positive(current, "entitlement_version") != billingEvent.entitlementVersion() + || !Objects.equals( + current.get("gameplay_available", Boolean.class), billingEvent.gameplayAvailable()) + || !Objects.equals( + current.get("allow_public_join", Boolean.class), billingEvent.allowPublicJoin()) + || !Objects.equals( + current.get("allow_new_gameplay_bindings", Boolean.class), + billingEvent.allowNewGameplayBindings()) + || !Objects.equals( + current.get("allow_new_instance_starts", Boolean.class), + billingEvent.allowNewInstanceStarts()) + || nonnegative(current, "max_active_sessions") != billingEvent.quotas().maxActiveSessions() + || nonnegative(current, "max_concurrent_game_instances") + != billingEvent.quotas().maxConcurrentGameInstances() + || nonnegative(current, "max_storage_bytes") != billingEvent.quotas().maxStorageBytes()) { + throw new IllegalStateException( + "Current tenant entitlement row differs from its exact committed billing event"); + } + return event; + } + + private static FreshTenantCreationEvidence sourceFromCurrent(UUID tenantId, Record current) { + return new FreshTenantCreationEvidence( + current.get("source_schema_version", Integer.class), + requiredText(current, "source_target_namespace"), + requiredUuid(current, "source_creation_request_id"), + requiredUuid(current, "source_operation_id"), + requiredText(current, "source_request_digest"), + tenantId, + positive(current, "source_game_row_id"), + requiredText(current, "source_game_tenant_key"), + requiredText(current, "source_provenance_kind"), + requiredText(current, "source_evidence_digest")); + } + + private static AccountAuthorityOutboxRepository.EventEvidence evidence(Event event) { + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId().toString(), event.eventDigest(), event.payload()); + } + + private static void requireExactTenant( + UUID tenantId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTenant(tenantId); + if (source == null + || authority == null + || !tenantId.equals(source.canonicalTenantId()) + || !AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId) + .equals(authority.scope()) + || authority.generation() <= 0L + || authority.sourceVersion() <= 0L) { + throw new IllegalArgumentException("Exact fresh tenant authority evidence is required"); + } + } + + private static void requireTenant(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("Exact tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Tenant authority event operation requires the Account owner transaction"); + } + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long increment(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant authority " + field + " is exhausted", overflow); + } + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java new file mode 100644 index 0000000000..a5f7971da6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-owned per-tenant billing/entitlement event stream for demo entitlement currentness. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Account transaction collaborator.") +public class AccountTenantEntitlementOutboxRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; Spring must proxy this non-final repository.") + public AccountTenantEntitlementOutboxRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public static String streamKey(UUID canonicalTenantId) { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException( + "Canonical tenant UUID is required for entitlement stream"); + } + return "account:tenant-entitlement:v1:tenant/" + canonicalTenantId; + } + + /** Appends one event or returns only an exact request and payload replay. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append(UUID tenantId, UUID requestId, LongFunction eventFactory) { + requireTransaction(); + streamKey(tenantId); + if (requestId == null || NIL_UUID.equals(requestId) || eventFactory == null) { + throw new IllegalArgumentException( + "Exact entitlement request identity and event are required"); + } + String key = streamKey(tenantId); + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_streams (tenant_uuid, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR UPDATE", + tenantId); + long currentSequence = nonnegative(stream, "last_sequence"); + Record priorRequest = + dsl.fetchOne( + "SELECT tenant_billing_sequence, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND request_id = ?", + tenantId, + requestId); + if (priorRequest != null) { + Event committed = event(tenantId, priorRequest); + Event candidate = + Objects.requireNonNull(eventFactory.apply(committed.tenantBillingSequence())); + if (!matches(committed, candidate) || currentSequence < committed.tenantBillingSequence()) { + throw new DemoTenantEntitlementException( + DemoTenantEntitlementException.Code.IDEMPOTENCY_CONFLICT, + "Tenant entitlement outbox request was reused with different event evidence"); + } + return committed; + } + + long nextSequence; + try { + nextSequence = Math.addExact(currentSequence, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant entitlement event sequence is exhausted", overflow); + } + Event candidate = Objects.requireNonNull(eventFactory.apply(nextSequence)); + if (!tenantId.equals(candidate.canonicalTenantId()) + || !requestId.equals(candidate.requestId()) + || !key.equals(candidate.outboxStreamKey()) + || candidate.tenantBillingSequence() != nextSequence) { + throw new IllegalArgumentException("Tenant entitlement event differs from its exact stream"); + } + Record advanced = + dsl.fetchOne( + "UPDATE account_tenant_entitlement_outbox_streams SET last_sequence = ? " + + "WHERE tenant_uuid = ? AND last_sequence = ? RETURNING last_sequence", + nextSequence, + tenantId, + currentSequence); + if (advanced == null) { + throw new IllegalStateException("Tenant entitlement outbox stream changed concurrently"); + } + int inserted = + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_events " + + "(tenant_uuid, tenant_billing_sequence, request_id, event_id, event_digest, payload) " + + "VALUES (?, ?, ?, ?, ?, ?)", + tenantId, + nextSequence, + requestId, + candidate.eventId(), + candidate.eventDigest(), + candidate.payload()); + if (inserted != 1) { + throw new IllegalStateException("Tenant entitlement outbox event was not appended"); + } + return candidate; + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCheckpoint(UUID tenantId) { + requireTransaction(); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (stream == null || nonnegative(stream, "last_sequence") == 0L) { + return Optional.empty(); + } + long sequence = positive(stream, "last_sequence"); + Event event = + readEvent(tenantId, sequence) + .orElseThrow( + () -> new IllegalStateException("Tenant entitlement checkpoint has no event")); + return Optional.of( + new Checkpoint( + streamKey(tenantId), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readEvent(UUID tenantId, long sequence) { + requireTransaction(); + if (sequence <= 0L) { + throw new IllegalArgumentException("Tenant entitlement event sequence must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT tenant_billing_sequence, request_id, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + tenantId, + sequence); + return row == null ? Optional.empty() : Optional.of(event(tenantId, row)); + } + + private Event event(UUID tenantId, Record row) { + byte[] payload = row.get("payload", byte[].class); + Event event = DemoTenantEntitlementEventV1Codec.verify(payload); + if (!tenantId.equals(event.canonicalTenantId()) + || row.get("tenant_billing_sequence", Long.class) != event.tenantBillingSequence() + || !row.get("event_id", UUID.class).equals(event.eventId()) + || !row.get("event_digest", String.class).equals(event.eventDigest()) + || !row.get("request_id", UUID.class).equals(event.requestId())) { + throw new IllegalStateException("Stored tenant entitlement event differs from its payload"); + } + return event; + } + + private static boolean matches(Event left, Event right) { + return left.eventId().equals(right.eventId()) + && left.eventDigest().equals(right.eventDigest()) + && java.util.Arrays.equals(left.payload(), right.payload()); + } + + private static long positive(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Tenant entitlement outbox requires an owner transaction"); + } + } + + public record Checkpoint( + String outboxStreamKey, long sequence, UUID eventId, String eventDigest) { + public Checkpoint { + if (outboxStreamKey == null || sequence <= 0L || eventId == null || eventDigest == null) { + throw new IllegalArgumentException("Complete tenant entitlement checkpoint is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java new file mode 100644 index 0000000000..68af647d9d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository.CurrentSnapshot; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Produces current, non-admitting Account evidence for public-production actor staging. */ +@Service +public class AccountActorStagingEligibilityService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountActorStagingEligibilityRepository sourceRepository; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Spring must proxy the read service and its source repository is required.") + public AccountActorStagingEligibilityService( + AccountActorStagingEligibilityRepository sourceRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.sourceRepository = Objects.requireNonNull(sourceRepository); + this.workloadNamespace = workloadNamespace; + } + + /** + * Resolves one exact request inside a single repeatable-read owner snapshot. The result is only + * staging evidence; it neither enrolls a member nor grants JOIN, PLAY, or admission authority. + */ + @Transactional( + readOnly = true, + isolation = Isolation.REPEATABLE_READ, + propagation = Propagation.REQUIRES_NEW) + public AccountActorStagingEligibilityEvidence resolve( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID accountUuid, + UUID tenantUuid, + Purpose purpose) { + if (schemaVersion != AccountActorStagingEligibilityEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported actor-staging eligibility schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !workloadNamespace.equals(targetNamespace) + || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException( + "Actor-staging eligibility target must match the configured Account namespace"); + } + requireCanonicalUuid(requestId, "request ID"); + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + if (purpose != Purpose.PUBLIC_PRODUCTION_STAGING_ONLY) { + throw new IllegalArgumentException("Only public-production actor staging is supported"); + } + + CurrentSnapshot snapshot = sourceRepository.readCurrent(accountUuid, tenantUuid); + if (!accountUuid.equals(snapshot.accountUuid()) || !tenantUuid.equals(snapshot.tenantUuid())) { + throw new IllegalStateException("Account owner snapshot differs from the requested scope"); + } + try { + return AccountActorStagingEligibilityEvidence.seal( + targetNamespace, + requestId, + accountUuid, + tenantUuid, + purpose, + Instant.now(), + snapshot.accountUuidProvenance().name(), + snapshot.accountLifecycleState(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipAuthorityProvenance(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.tenantProvenanceKind(), + snapshot.tenantSourceOperationId(), + snapshot.tenantProvenanceDigest(), + snapshot.membershipEventSequence(), + snapshot.membershipEventId(), + snapshot.membershipEventDigest(), + snapshot.lastTransitionInvalidated()); + } catch (IllegalArgumentException invalidOwnerEvidence) { + throw new IllegalStateException( + "Account owner snapshot cannot produce valid staging evidence", invalidOwnerEvidence); + } + } + + private static void requireCanonicalUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical nonnil UUID"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java new file mode 100644 index 0000000000..f0950da2b1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.accountservice.service; + +/** Typed fail-closed outcomes for Account's protected non-paid demo entitlement slice. */ +public final class DemoTenantEntitlementException extends IllegalStateException { + private final Code code; + + public DemoTenantEntitlementException(Code code, String message) { + super(message); + this.code = code; + } + + public DemoTenantEntitlementException(Code code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public Code code() { + return code; + } + + public enum Code { + FIXTURE_DISABLED, + ENVIRONMENT_DENIED, + SOURCE_EVIDENCE_INVALID, + IDEMPOTENCY_CONFLICT, + ENTITLEMENT_VERSION_CONFLICT, + TENANT_AUTHORITY_STALE, + ENTITLEMENT_UNAVAILABLE, + STALE_ADMISSION_EVIDENCE + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java new file mode 100644 index 0000000000..f335565c55 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java @@ -0,0 +1,214 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.Timestamp; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountActorStagingEligibilityServiceGrpc; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityCurrentness; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityDecision; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityPurpose; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityRequest; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityResponse; +import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Currentness; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Decision; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.jooq.exception.TooManyRowsException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; + +/** Same-namespace Entity-only mTLS transport for Account staging evidence, disabled by default. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.actor-staging-eligibility", + name = "enabled", + havingValue = "true") +public class AccountActorStagingEligibilityGrpcService + extends AccountActorStagingEligibilityServiceGrpc + .AccountActorStagingEligibilityServiceImplBase { + private final AccountActorStagingEligibilityService eligibilityService; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Fail closed when the required internal owner service is absent.") + public AccountActorStagingEligibilityGrpcService( + AccountActorStagingEligibilityService eligibilityService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.eligibilityService = Objects.requireNonNull(eligibilityService); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolvePreseededActorStagingEligibility( + ResolvePreseededActorStagingEligibilityRequest request, + StreamObserver responseObserver) { + if (!isAllowedEntityPeer()) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Entity Management workload identity is required"); + return; + } + if (request.getSchemaVersion() != AccountActorStagingEligibilityEvidence.SCHEMA_VERSION + || !workloadNamespace.equals(request.getTargetNamespace()) + || !GrpcPeerIdentity.isValidNamespace(request.getTargetNamespace()) + || !request.getUnknownFields().asMap().isEmpty()) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "The exact actor-staging request schema and Account namespace are required"); + return; + } + + UUID requestId = AccountUuidText.parseOrNull(request.getRequestId()); + UUID accountUuid = AccountUuidText.parseOrNull(request.getCanonicalAccountId()); + UUID tenantUuid = AccountUuidText.parseOrNull(request.getCanonicalTenantId()); + Purpose purpose = decodePurpose(request.getPurpose()); + if (requestId == null || accountUuid == null || tenantUuid == null || purpose == null) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical nonnil IDs and public-production staging purpose are required"); + return; + } + + final AccountActorStagingEligibilityEvidence evidence; + try { + evidence = + eligibilityService.resolve( + request.getSchemaVersion(), + request.getTargetNamespace(), + requestId, + accountUuid, + tenantUuid, + purpose); + } catch (DataAccessResourceFailureException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Account owner evidence is temporarily unavailable"); + return; + } catch (IllegalStateException + | IllegalArgumentException + | TooManyRowsException invalidOwnerState) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Current Account membership evidence is absent or contradictory"); + return; + } catch (DataAccessException failure) { + fail( + responseObserver, + hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL, + hasConnectionFailureSqlState(failure) + ? "Account owner evidence is temporarily unavailable" + : "Account owner evidence could not be read"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Account owner evidence could not be produced"); + return; + } + + responseObserver.onNext(toResponse(evidence)); + responseObserver.onCompleted(); + } + + private boolean isAllowedEntityPeer() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace.equals(peer.namespace()) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service"); + } + + private static Purpose decodePurpose(ActorStagingEligibilityPurpose purpose) { + return purpose == ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY + ? Purpose.PUBLIC_PRODUCTION_STAGING_ONLY + : null; + } + + private static ResolvePreseededActorStagingEligibilityResponse toResponse( + AccountActorStagingEligibilityEvidence evidence) { + return ResolvePreseededActorStagingEligibilityResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(evidence.requestId().toString()) + .setCanonicalAccountId(evidence.canonicalAccountId().toString()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setPurpose(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) + .setCurrentness(toWireCurrentness(evidence.currentness())) + .setObservedAt(timestamp(evidence.observedAt())) + .setDecision(toWireDecision(evidence.decision())) + .setAccountUuidProvenance(evidence.accountUuidProvenance()) + .setAccountLifecycleState(evidence.accountLifecycleState()) + .setMembershipLifecycleState(evidence.membershipLifecycleState()) + .setGameplayAdmissionAllowed(evidence.gameplayAdmissionAllowed()) + .setMembershipAuthorityProvenance(evidence.membershipAuthorityProvenance()) + .setMembershipVersion(evidence.membershipVersion()) + .setMembershipAuthorityGeneration(evidence.membershipAuthorityGeneration()) + .setTenantProvenanceKind(evidence.tenantProvenanceKind()) + .setTenantSourceOperationId(evidence.tenantSourceOperationId().toString()) + .setTenantProvenanceDigest(evidence.tenantProvenanceDigest()) + .setMembershipEventSequence(evidence.membershipEventSequence()) + .setMembershipEventId(evidence.membershipEventId().toString()) + .setMembershipEventDigest(evidence.membershipEventDigest()) + .setLastTransitionInvalidated(evidence.lastTransitionInvalidated()) + .setEligibilityDecisionDigest(evidence.eligibilityDecisionDigest()) + .setAuthoritySnapshotDigest(evidence.authoritySnapshotDigest()) + .build(); + } + + private static ActorStagingEligibilityCurrentness toWireCurrentness(Currentness currentness) { + if (currentness == Currentness.CURRENT_AT_REVALIDATION) { + return ActorStagingEligibilityCurrentness.CURRENT_AT_REVALIDATION; + } + throw new IllegalStateException("Account produced unsupported actor-staging currentness"); + } + + private static ActorStagingEligibilityDecision toWireDecision(Decision decision) { + return switch (decision) { + case STAGING_ELIGIBLE -> ActorStagingEligibilityDecision.STAGING_ELIGIBLE; + case STAGING_INELIGIBLE -> ActorStagingEligibilityDecision.STAGING_INELIGIBLE; + }; + } + + private static Timestamp timestamp(java.time.Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static void fail( + StreamObserver responseObserver, + Status status, + String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 130c82c21d..e8742830ac 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -77,6 +77,7 @@ firemud: - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity + - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 027fc23c34..83aed7dc83 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -55,6 +55,8 @@ firemud: player-bootstrap-expiration-ms: 300000 connect-scope-expiration-ms: 120000 connect-token-expiration-ms: 30000 + actor-staging-eligibility: + enabled: ${FIREMUD_ACCOUNT_ACTOR_STAGING_ELIGIBILITY_ENABLED:false} mail: from: no-reply@firemud.local verification-url: http://localhost:8080/auth/verify-email?token=%s @@ -104,6 +106,7 @@ firemud: - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity + - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility management: endpoints: diff --git a/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql new file mode 100644 index 0000000000..3c9fdf95bb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql @@ -0,0 +1,427 @@ +-- Explicit, protected-fixture-only non-paid entitlement state. Tenant identity is UUID-native; +-- source row IDs are retained solely as authenticated provenance. +CREATE TABLE account_tenant_entitlement_outbox_streams ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + last_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_sequence >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE account_tenant_entitlement_outbox_events ( + tenant_uuid UUID NOT NULL, + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_id UUID NOT NULL UNIQUE CHECK (event_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_uuid, tenant_billing_sequence), + UNIQUE (tenant_uuid, request_id), + UNIQUE (tenant_uuid, tenant_billing_sequence, event_id, event_digest), + FOREIGN KEY (tenant_uuid) REFERENCES account_tenant_entitlement_outbox_streams (tenant_uuid) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlement_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + tenant_uuid UUID NOT NULL + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_creation_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED')), + tenant_billing_sequence BIGINT, + event_id UUID, + event_digest VARCHAR(71), + entitlement_version BIGINT, + tenant_authority_generation BIGINT, + tenant_authority_source_version BIGINT, + committed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_demo_entitlement_operation_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_billing_sequence IS NULL AND event_id IS NULL + AND event_digest IS NULL AND entitlement_version IS NULL + AND tenant_authority_generation IS NULL AND tenant_authority_source_version IS NULL + AND committed_at IS NULL) + OR + (status = 'COMMITTED' AND tenant_billing_sequence IS NOT NULL AND tenant_billing_sequence > 0 + AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_version IS NOT NULL AND entitlement_version > 0 + AND tenant_authority_generation IS NOT NULL AND tenant_authority_generation > 0 + AND tenant_authority_source_version IS NOT NULL AND tenant_authority_source_version > 0 + AND committed_at IS NOT NULL) + ), + UNIQUE (tenant_uuid, request_id), + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlements ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + source_target_namespace VARCHAR(128) NOT NULL + CHECK (source_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + source_creation_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_game_row_id BIGINT NOT NULL CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + source_provenance_kind VARCHAR(32) NOT NULL CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + entitlement_kind VARCHAR(32) NOT NULL DEFAULT 'NON_PAID_DEMO' CHECK (entitlement_kind = 'NON_PAID_DEMO'), + status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' CHECK (status = 'ACTIVE'), + subscription_status VARCHAR(32) CHECK (subscription_status IS NULL), + paid BOOLEAN NOT NULL DEFAULT FALSE CHECK (paid = FALSE), + gameplay_available BOOLEAN NOT NULL, + allow_public_join BOOLEAN NOT NULL, + allow_new_gameplay_bindings BOOLEAN NOT NULL, + allow_new_instance_starts BOOLEAN NOT NULL, + max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), + max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), + max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), + entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), + tenant_authority_generation BIGINT NOT NULL CHECK (tenant_authority_generation > 0), + tenant_authority_source_version BIGINT NOT NULL CHECK (tenant_authority_source_version > 0), + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + event_id UUID NOT NULL, + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + last_request_id UUID NOT NULL, + last_request_digest VARCHAR(71) NOT NULL CHECK (last_request_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (tenant_uuid, last_request_id) + REFERENCES account_demo_tenant_entitlement_operations (tenant_uuid, request_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_entitlement_stream_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.last_sequence <> 0 THEN + RAISE EXCEPTION 'Tenant entitlement stream must begin at sequence zero' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.last_sequence <> OLD.last_sequence + 1 THEN + RAISE EXCEPTION 'Tenant entitlement stream is immutable and advances by exactly one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_outbox_event_guard() RETURNS trigger AS $$ +DECLARE + current_sequence BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Tenant entitlement outbox events are immutable' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = NEW.tenant_uuid; + IF current_sequence IS DISTINCT FROM NEW.tenant_billing_sequence THEN + RAISE EXCEPTION 'Tenant entitlement event does not match its stream checkpoint' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_stream_consistency() RETURNS trigger AS $$ +DECLARE + stream_tenant UUID; + stream_sequence BIGINT; + max_sequence BIGINT; + event_count BIGINT; +BEGIN + stream_tenant := COALESCE(NEW.tenant_uuid, OLD.tenant_uuid); + SELECT last_sequence INTO stream_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = stream_tenant; + SELECT COALESCE(MAX(tenant_billing_sequence), 0), COUNT(*) + INTO max_sequence, event_count FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = stream_tenant; + IF stream_sequence IS NULL OR stream_sequence <> max_sequence OR stream_sequence <> event_count THEN + RAISE EXCEPTION 'Tenant entitlement outbox stream and events are inconsistent' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Demo entitlement operation must start pending' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' OR OLD.status <> 'PENDING' OR NEW.status <> 'COMMITTED' + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_guard() RETURNS trigger AS $$ +DECLARE + authority_generation BIGINT; + authority_source_version BIGINT; + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Demo entitlement state cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.source_schema_version IS DISTINCT FROM OLD.source_schema_version + OR NEW.source_target_namespace IS DISTINCT FROM OLD.source_target_namespace + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest + OR NEW.entitlement_version <> OLD.entitlement_version + 1 THEN + RAISE EXCEPTION 'Demo entitlement identity is immutable and version advances by one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + ELSIF NEW.entitlement_version <> 1 THEN + RAISE EXCEPTION 'Demo entitlement must begin at version one' + USING ERRCODE = '23514'; + END IF; + SELECT generation, source_version INTO authority_generation, authority_source_version + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF authority_generation IS DISTINCT FROM NEW.tenant_authority_generation + OR authority_source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement is not fenced by current tenant authority' + USING ERRCODE = '23514'; + END IF; + SELECT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.schema_version = NEW.source_schema_version + AND fresh.target_namespace = NEW.source_target_namespace + AND fresh.creation_request_id = NEW.source_creation_request_id + AND fresh.operation_id = NEW.source_operation_id + AND fresh.request_digest = NEW.source_request_digest + AND fresh.source_game_row_id = NEW.source_game_row_id + AND fresh.source_game_tenant_key = NEW.source_game_tenant_key + AND fresh.provenance_kind = NEW.source_provenance_kind + AND fresh.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + IF NOT source_matches THEN + RAISE EXCEPTION 'Demo entitlement requires exact fresh Game Design source evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_terminal_guard() RETURNS trigger AS $$ +DECLARE + operation_status VARCHAR(16); + operation_tenant UUID; + operation_sequence BIGINT; + operation_event_id UUID; + operation_event_digest VARCHAR(71); + operation_request_digest VARCHAR(71); + operation_entitlement_version BIGINT; + operation_authority_generation BIGINT; + operation_authority_source_version BIGINT; + operation_source_creation_request_id UUID; + operation_source_request_digest VARCHAR(71); + operation_source_operation_id UUID; + operation_source_evidence_digest VARCHAR(71); + event_payload JSONB; +BEGIN + SELECT status, tenant_uuid, tenant_billing_sequence, event_id, event_digest, request_digest, + entitlement_version, tenant_authority_generation, tenant_authority_source_version, + source_creation_request_id, source_request_digest, source_operation_id, + source_evidence_digest + INTO operation_status, operation_tenant, operation_sequence, operation_event_id, + operation_event_digest, operation_request_digest, operation_entitlement_version, + operation_authority_generation, operation_authority_source_version, + operation_source_creation_request_id, operation_source_request_digest, + operation_source_operation_id, operation_source_evidence_digest + FROM account_demo_tenant_entitlement_operations + WHERE request_id = NEW.request_id; + IF operation_status IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Demo entitlement operation cannot commit pending' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO event_payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = operation_tenant + AND event.tenant_billing_sequence = operation_sequence + AND event.event_id = operation_event_id + AND event.event_digest = operation_event_digest; + IF event_payload IS NULL + OR event_payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR event_payload->>'requestDigest' IS DISTINCT FROM operation_request_digest + OR event_payload->>'tenantId' IS DISTINCT FROM operation_tenant::TEXT + OR event_payload->>'tenantBillingSequence' IS DISTINCT FROM operation_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM operation_event_id::TEXT + OR event_payload->>'eventDigest' IS DISTINCT FROM operation_event_digest + OR event_payload->>'entitlementVersion' IS DISTINCT FROM operation_entitlement_version::TEXT + OR event_payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM operation_authority_generation::TEXT + OR event_payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM operation_authority_source_version::TEXT + OR event_payload->'sourceEvidence'->>'creationRequestId' + IS DISTINCT FROM operation_source_creation_request_id::TEXT + OR event_payload->'sourceEvidence'->>'requestDigest' + IS DISTINCT FROM operation_source_request_digest + OR event_payload->'sourceEvidence'->>'operationId' + IS DISTINCT FROM operation_source_operation_id::TEXT + OR event_payload->'sourceEvidence'->>'evidenceDigest' + IS DISTINCT FROM operation_source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation receipt differs from its exact event' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = operation_tenant + AND fresh.creation_request_id = operation_source_creation_request_id + AND fresh.request_digest = operation_source_request_digest + AND fresh.operation_id = operation_source_operation_id + AND fresh.evidence_digest = operation_source_evidence_digest + AND fresh.provenance_kind = 'NEW_GAME_ROW' + ) THEN + RAISE EXCEPTION 'Demo entitlement operation has no exact fresh tenant source' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_event_guard() RETURNS trigger AS $$ +DECLARE + payload JSONB; +BEGIN + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = NEW.tenant_uuid + AND event.tenant_billing_sequence = NEW.tenant_billing_sequence + AND event.event_id = NEW.event_id + AND event.event_digest = NEW.event_digest; + IF payload IS NULL + OR payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-entitlement-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_ENTITLEMENT_CHANGED' + OR payload->>'outboxStreamKey' IS DISTINCT FROM + ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantBillingSequence' IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.event_id::TEXT + OR payload->>'eventDigest' IS DISTINCT FROM NEW.event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'entitlementKind' IS DISTINCT FROM NEW.entitlement_kind + OR payload->>'status' IS DISTINCT FROM NEW.status + OR payload->>'paid' IS DISTINCT FROM 'false' + OR payload->>'gameplayAvailable' IS DISTINCT FROM NEW.gameplay_available::TEXT + OR payload->>'allowPublicJoin' IS DISTINCT FROM NEW.allow_public_join::TEXT + OR payload->>'allowNewGameplayBindings' IS DISTINCT FROM NEW.allow_new_gameplay_bindings::TEXT + OR payload->>'allowNewInstanceStarts' IS DISTINCT FROM NEW.allow_new_instance_starts::TEXT + OR payload->'quotas'->>'maxActiveSessions' IS DISTINCT FROM NEW.max_active_sessions::TEXT + OR payload->'quotas'->>'maxConcurrentGameInstances' IS DISTINCT FROM NEW.max_concurrent_game_instances::TEXT + OR payload->'quotas'->>'maxStorageBytes' IS DISTINCT FROM NEW.max_storage_bytes::TEXT + OR payload->'sourceEvidence'->>'schemaVersion' IS DISTINCT FROM NEW.source_schema_version::TEXT + OR payload->'sourceEvidence'->>'targetNamespace' IS DISTINCT FROM NEW.source_target_namespace + OR payload->'sourceEvidence'->>'creationRequestId' IS DISTINCT FROM NEW.source_creation_request_id::TEXT + OR payload->'sourceEvidence'->>'operationId' IS DISTINCT FROM NEW.source_operation_id::TEXT + OR payload->'sourceEvidence'->>'requestDigest' IS DISTINCT FROM NEW.source_request_digest + OR payload->'sourceEvidence'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->'sourceEvidence'->>'sourceGameRowId' IS DISTINCT FROM NEW.source_game_row_id::TEXT + OR payload->'sourceEvidence'->>'sourceGameTenantKey' IS DISTINCT FROM NEW.source_game_tenant_key + OR payload->'sourceEvidence'->>'provenanceKind' IS DISTINCT FROM NEW.source_provenance_kind + OR payload->'sourceEvidence'->>'evidenceDigest' IS DISTINCT FROM NEW.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement state differs from its canonical outbox event' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_reject_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account demo entitlement history cannot be truncated' + USING ERRCODE = '23514'; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_tenant_entitlement_stream_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_streams + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_stream_guard(); +CREATE TRIGGER account_tenant_entitlement_stream_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_streams + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE TRIGGER account_tenant_entitlement_event_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_events + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_outbox_event_guard(); +CREATE TRIGGER account_tenant_entitlement_event_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_events + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_stream + AFTER INSERT OR UPDATE ON account_tenant_entitlement_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_event + AFTER INSERT ON account_tenant_entitlement_outbox_events + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_operation_guard(); +CREATE TRIGGER account_demo_entitlement_operation_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlement_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_operation_terminal + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_operation_terminal_guard(); +CREATE TRIGGER account_demo_entitlement_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_current_guard(); +CREATE TRIGGER account_demo_entitlement_current_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlements + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_current_event + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlements + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_current_event_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql new file mode 100644 index 0000000000..1b641d4d2e --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -0,0 +1,482 @@ +-- Preserve source-owner initialization provenance for future exact tenant-authority enrollment. +-- Existing rows remain NULL and are deliberately not assigned a synthetic generation-one proof. +ALTER TABLE account_fresh_tenant_identity_associations + ADD COLUMN authority_source_transaction_id BIGINT; +ALTER TABLE account_fresh_tenant_identity_associations + ADD CONSTRAINT account_fresh_tenant_authority_source_transaction_check + CHECK (authority_source_transaction_id IS NULL OR authority_source_transaction_id > 0); + +-- This is an Account-owned typed head over the generic authority outbox, not a second event log. +-- A sequence-zero row exists only inside the first authority transaction and cannot commit. +CREATE TABLE account_tenant_authority_source_records ( + outbox_stream_key VARCHAR(2048) PRIMARY KEY + REFERENCES account_authority_outbox_streams (outbox_stream_key) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL UNIQUE + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + initialization_transaction_id BIGINT NOT NULL CHECK (initialization_transaction_id > 0), + baseline_generation BIGINT NOT NULL DEFAULT 1 CHECK (baseline_generation = 1), + baseline_source_version BIGINT NOT NULL DEFAULT 1 CHECK (baseline_source_version = 1), + current_generation BIGINT NOT NULL CHECK (current_generation > 0), + current_source_version BIGINT NOT NULL CHECK (current_source_version > 0), + last_outbox_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_outbox_sequence >= 0), + last_request_id UUID, + last_request_digest VARCHAR(71), + last_event_id VARCHAR(512), + last_event_digest VARCHAR(71), + tenant_billing_sequence BIGINT, + tenant_billing_event_id UUID, + tenant_billing_event_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_tenant_authority_source_key_check CHECK ( + outbox_stream_key = 'account:auth-authority:v1:tenant/' || tenant_uuid::TEXT), + CONSTRAINT account_tenant_authority_source_version_check CHECK ( + current_generation = baseline_generation + last_outbox_sequence + AND current_source_version = baseline_source_version + last_outbox_sequence), + CONSTRAINT account_tenant_authority_source_head_check CHECK ( + (last_outbox_sequence = 0 AND last_request_id IS NULL AND last_request_digest IS NULL + AND last_event_id IS NULL AND last_event_digest IS NULL + AND tenant_billing_sequence IS NULL AND tenant_billing_event_id IS NULL + AND tenant_billing_event_digest IS NULL) + OR (last_outbox_sequence > 0 AND last_request_id IS NOT NULL + AND last_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND last_event_id IS NOT NULL AND length(btrim(last_event_id)) > 0 + AND last_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND tenant_billing_sequence > 0 AND tenant_billing_event_id IS NOT NULL + AND tenant_billing_event_digest ~ '^sha256:[0-9a-f]{64}$')) +); + +ALTER TABLE account_demo_tenant_entitlement_operations + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source receipt constraint. +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_entitlement_authority_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_authority_outbox_stream_key IS NULL + AND tenant_authority_outbox_sequence IS NULL AND tenant_authority_event_id IS NULL + AND tenant_authority_event_digest IS NULL) + OR (status = 'COMMITTED' AND tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 + AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_tenant_entitlement_operations_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE account_demo_tenant_entitlements + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source head constraint. +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_entitlement_authority_head_shape CHECK ( + (tenant_authority_outbox_stream_key IS NULL AND tenant_authority_outbox_sequence IS NULL + AND tenant_authority_event_id IS NULL AND tenant_authority_event_digest IS NULL) + OR (tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_tenant_entitlements_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +-- Only Account's fresh tenant import path stamps this transaction ID. Retained rows are untouched. +-- [jooq ignore start] +CREATE FUNCTION account_fresh_tenant_authority_source_transaction_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.authority_source_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_fresh_tenant_authority_source_transaction + BEFORE INSERT ON account_fresh_tenant_identity_associations + FOR EACH ROW EXECUTE FUNCTION account_fresh_tenant_authority_source_transaction_guard(); + +CREATE FUNCTION account_tenant_authority_source_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + fresh_row RECORD; + generation_row RECORD; + stream_sequence BIGINT; +BEGIN + SELECT authority_source_transaction_id, provenance_kind INTO fresh_row + FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + SELECT generation, source_version, created_transaction_id INTO generation_row + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF NEW.outbox_stream_key <> 'account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT + OR NEW.initialization_transaction_id IS NULL + OR fresh_row.authority_source_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR fresh_row.provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR generation_row.created_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR generation_row.generation IS DISTINCT FROM 1 + OR generation_row.source_version IS DISTINCT FROM 1 + OR stream_sequence IS DISTINCT FROM 0 + OR NEW.baseline_generation IS DISTINCT FROM 1 + OR NEW.baseline_source_version IS DISTINCT FROM 1 + OR NEW.current_generation IS DISTINCT FROM 1 + OR NEW.current_source_version IS DISTINCT FROM 1 + OR NEW.last_outbox_sequence IS DISTINCT FROM 0 + OR NEW.last_event_id IS NOT NULL OR NEW.last_event_digest IS NOT NULL + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key) THEN + RAISE EXCEPTION 'Tenant authority baseline lacks fresh Account source initialization proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_baseline'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + billing_event RECORD; + fresh_row RECORD; +BEGIN + IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.initialization_transaction_id IS DISTINCT FROM OLD.initialization_transaction_id + OR NEW.baseline_generation IS DISTINCT FROM OLD.baseline_generation + OR NEW.baseline_source_version IS DISTINCT FROM OLD.baseline_source_version + OR NEW.last_outbox_sequence <> OLD.last_outbox_sequence + 1 + OR NEW.current_generation <> OLD.current_generation + 1 + OR NEW.current_source_version <> OLD.current_source_version + 1 + OR NEW.current_generation <> NEW.baseline_generation + NEW.last_outbox_sequence + OR NEW.current_source_version <> NEW.baseline_source_version + NEW.last_outbox_sequence + OR NEW.last_request_id IS NULL OR NEW.last_request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_event_id IS NULL OR NEW.last_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.tenant_billing_sequence IS NULL OR NEW.tenant_billing_sequence <= 0 + OR NEW.tenant_billing_event_id IS NULL + OR NEW.tenant_billing_event_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Tenant authority source must advance one exact immutable event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_monotonic'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.last_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.last_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source head differs from its exact event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.last_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.last_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.last_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.tenant_billing_event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority source event does not match its exact checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_values'; + END IF; + SELECT schema_version, target_namespace, creation_request_id, operation_id, request_digest, + source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest + INTO fresh_row FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + IF payload#>>'{sourceEvidence,schemaVersion}' IS DISTINCT FROM fresh_row.schema_version::TEXT + OR payload#>>'{sourceEvidence,targetNamespace}' IS DISTINCT FROM fresh_row.target_namespace + OR payload#>>'{sourceEvidence,creationRequestId}' IS DISTINCT FROM fresh_row.creation_request_id::TEXT + OR payload#>>'{sourceEvidence,operationId}' IS DISTINCT FROM fresh_row.operation_id::TEXT + OR payload#>>'{sourceEvidence,requestDigest}' IS DISTINCT FROM fresh_row.request_digest + OR payload#>>'{sourceEvidence,canonicalTenantId}' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload#>>'{sourceEvidence,sourceGameRowId}' IS DISTINCT FROM fresh_row.source_game_row_id::TEXT + OR payload#>>'{sourceEvidence,sourceGameTenantKey}' IS DISTINCT FROM fresh_row.source_game_tenant_key + OR payload#>>'{sourceEvidence,provenanceKind}' IS DISTINCT FROM fresh_row.provenance_kind + OR payload#>>'{sourceEvidence,evidenceDigest}' IS DISTINCT FROM fresh_row.evidence_digest THEN + RAISE EXCEPTION 'Tenant authority event differs from fresh Game Design source evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_evidence'; + END IF; + SELECT billing_event_row.event_id, billing_event_row.event_digest, + billing_event_row.payload INTO billing_event + FROM account_tenant_entitlement_outbox_events AS billing_event_row + WHERE billing_event_row.tenant_uuid = NEW.tenant_uuid + AND billing_event_row.tenant_billing_sequence = NEW.tenant_billing_sequence; + IF billing_event.event_id IS DISTINCT FROM NEW.tenant_billing_event_id + OR billing_event.event_digest IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority event does not link to the exact tenant billing event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_billing_link'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + head RECORD; + generation_row RECORD; + stream_sequence BIGINT; + operation_row RECORD; + entitlement_row RECORD; +BEGIN + SELECT * INTO head FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 + OR head.current_generation IS DISTINCT FROM generation_row.generation + OR head.current_source_version IS DISTINCT FROM generation_row.source_version + OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN + RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; + END IF; + SELECT request_id, tenant_uuid, request_digest, source_creation_request_id, + source_request_digest, source_operation_id, source_evidence_digest, status, + tenant_billing_sequence, event_id, event_digest, + tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, + tenant_authority_event_id, tenant_authority_event_digest + INTO operation_row FROM account_demo_tenant_entitlement_operations + WHERE request_id = head.last_request_id; + SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements + WHERE tenant_uuid = NEW.tenant_uuid; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest + OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest + OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation + OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version + OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_generation_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; +BEGIN + IF NEW.scope_kind = 'TENANT' THEN + SELECT current_generation, current_source_version INTO source_row + FROM account_tenant_authority_source_records WHERE tenant_uuid = NEW.tenant_uuid; + IF source_row.current_generation IS DISTINCT FROM NEW.generation + OR source_row.current_source_version IS DISTINCT FROM NEW.source_version THEN + RAISE EXCEPTION 'Tenant authority generation advance lacks its canonical source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_generation_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_stream_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; + stream_head BIGINT; +BEGIN + IF left(NEW.outbox_stream_key, length('account:auth-authority:v1:tenant/')) + = 'account:auth-authority:v1:tenant/' THEN + -- This is deferred: the queued NEW image may be the temporary sequence-zero row + -- created while the first source head is enrolled. Validate the final live head instead. + SELECT last_sequence INTO stream_head + FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT last_outbox_sequence INTO source_row + FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF stream_head IS NULL + OR source_row.last_outbox_sequence IS DISTINCT FROM stream_head + OR stream_head <= 0 THEN + RAISE EXCEPTION 'Tenant authority outbox head lacks an Account-owned source checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_stream_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_event_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + generation_row RECORD; +BEGIN + IF NEW.tenant_authority_outbox_stream_key IS NULL + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Demo entitlement requires a distinct canonical tenant authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_required'; + END IF; + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) THEN + RAISE EXCEPTION 'Demo entitlement tenant authority event has the wrong scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_scope'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Demo entitlement authority receipt differs from its exact source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.tenant_authority_outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.tenant_authority_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.tenant_authority_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.tenant_authority_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest + OR generation_row.generation IS DISTINCT FROM NEW.tenant_authority_generation + OR generation_row.source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement differs from its actual tenant authority source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_values'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_receipt_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; +BEGIN + IF NEW.status = 'COMMITTED' THEN + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Committed demo receipt requires its exact tenant authority checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_required'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Committed demo receipt authority event differs from Account outbox' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_event'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest THEN + RAISE EXCEPTION 'Committed demo receipt differs from its canonical authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_values'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_tenant_authority_source_insert + BEFORE INSERT ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_insert_guard(); +CREATE TRIGGER account_tenant_authority_source_update + BEFORE UPDATE OR DELETE ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_update_guard(); +CREATE TRIGGER account_tenant_authority_source_no_truncate + BEFORE TRUNCATE ON account_tenant_authority_source_records + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_source_consistency + AFTER INSERT OR UPDATE ON account_tenant_authority_source_records + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_source_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_generation_consistency + AFTER UPDATE ON account_authority_generations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_generation_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_stream_consistency + AFTER INSERT OR UPDATE ON account_authority_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_authority_event + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_event_guard(); +CREATE TRIGGER account_demo_entitlement_authority_receipt + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_receipt_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java new file mode 100644 index 0000000000..d43be29971 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -0,0 +1,629 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Physical PostgreSQL proof for exact-source demo entitlement commit and revalidation fencing. */ +class AccountDemoTenantEntitlementPersistenceIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static AccountPostgresIntegrationFixture postgresFixture; + private static DriverManagerDataSource rootDataSource; + private final Set runOwnedSchemas = new java.util.LinkedHashSet<>(); + + @BeforeAll + static void setUpPostgresFixture() { + postgresFixture = new AccountPostgresIntegrationFixture(); + postgresFixture.start(); + rootDataSource = postgresFixture.dataSource(); + } + + @AfterEach + void dropOnlyRunOwnedSchemas() { + JdbcTemplate rootJdbc = new JdbcTemplate(rootDataSource); + for (String schema : runOwnedSchemas) { + rootJdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @AfterAll + static void stopPostgresFixture() { + if (postgresFixture != null) { + postgresFixture.stop(); + } + } + + @Test + void sequenceZeroTenantAuthorityHeadCannotCommit() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository billingOutbox = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + new AccountAuthorityOutboxRepository(context.dsl()), + billingOutbox, + identityRepository, + generationRepository); + UUID tenantId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + UUID requestId = UUID.fromString("88888888-8888-4888-8888-888888888889"); + FreshTenantCreationEvidence source = evidence(tenantId, 805L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(source); + generationRepository.initializeTenantIfAbsent(tenantId); + return null; + }); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + tenantAuthorityEvents.establishFirstEventSource( + tenantId, + requestId, + source, + generationRepository.read( + AccountAuthorityGenerationRepository.AuthorityScope.tenant( + tenantId))); + context + .dsl() + .execute( + "SET CONSTRAINTS account_tenant_authority_stream_consistency IMMEDIATE"); + return null; + })) + .rootCause() + .hasMessageContaining( + "Tenant authority outbox head lacks an Account-owned source checkpoint"); + } + + @Test + void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenced() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository outboxRepository = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountAuthorityOutboxRepository authorityOutbox = + new AccountAuthorityOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + authorityOutbox, + outboxRepository, + identityRepository, + generationRepository); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + context.dsl(), + identityRepository, + generationRepository, + outboxRepository, + tenantAuthorityEvents); + + UUID tenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + FreshTenantCreationEvidence source = evidence(tenantId, 801L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(source); + generationRepository.initializeTenantIfAbsent(tenantId); + return null; + }); + + DemoTenantEntitlementRequest create = + request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + tenantId, + source, + null, + null, + null, + true); + DemoTenantEntitlementSnapshot first = + inTransaction(context.transaction(), () -> entitlements.provision(create, source)); + assertThat(first.canonicalTenantId()).isEqualTo(tenantId); + assertThat(first.sourceEvidence()).isEqualTo(source); + assertThat(first.entitlementKind()).isEqualTo("NON_PAID_DEMO"); + assertThat(first.status()).isEqualTo("ACTIVE"); + assertThat(first.subscriptionStatus()).isNull(); + assertThat(first.paid()).isFalse(); + assertThat(first.gameplayAvailable()).isTrue(); + assertThat(first.allowPublicJoin()).isFalse(); + assertThat(first.allowNewGameplayBindings()).isFalse(); + assertThat(first.allowNewInstanceStarts()).isTrue(); + assertThat(first.quotas()).isEqualTo(new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + assertThat(first.entitlementVersion()).isEqualTo(1L); + assertThat(first.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(first.tenantAuthoritySourceVersion()).isEqualTo(2L); + assertThat(first.tenantBillingSequence()).isEqualTo(1L); + assertThat(first.outboxStreamKey()) + .isEqualTo(AccountTenantEntitlementOutboxRepository.streamKey(tenantId)); + assertThat(first.tenantAuthorityOutboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantId); + assertThat(first.tenantAuthorityOutboxSequence()).isEqualTo(1L); + assertThat(first.tenantAuthorityEventId()).isNotNull(); + assertThat(first.tenantAuthorityEventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(first.tenantAuthorityEventId()).isNotEqualTo(first.eventId()); + + assertThat(inTransaction(context.transaction(), () -> entitlements.provision(create, source))) + .isEqualTo(first); + DemoTenantEntitlementSnapshot exactReadback = + inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId)); + assertThat(exactReadback).isEqualTo(first); + var authorityReadback = + inTransaction( + context.transaction(), () -> tenantAuthorityEvents.readCurrentByTenant(tenantId)); + assertThat(authorityReadback.eventId()).isEqualTo(first.tenantAuthorityEventId()); + assertThat(authorityReadback.eventDigest()).isEqualTo(first.tenantAuthorityEventDigest()); + assertThat(authorityReadback.outboxSequence()).isEqualTo(first.tenantAuthorityOutboxSequence()); + + DemoTenantEntitlementRequest conflictingReplay = + request(create.requestId(), tenantId, source, null, null, null, false); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(conflictingReplay, source))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("reused for a different tenant or payload"); + + FreshTenantCreationEvidence alteredProvenance = alteredProvenance(source); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(create, alteredProvenance))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("differs from exact Account UUID readback"); + + UUID otherTenantId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + FreshTenantCreationEvidence otherSource = evidence(otherTenantId, 802L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(otherSource); + generationRepository.initializeTenantIfAbsent(otherTenantId); + return null; + }); + DemoTenantEntitlementRequest crossTenantReplay = + request(create.requestId(), otherTenantId, otherSource, null, null, null, true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> entitlements.provision(crossTenantReplay, otherSource))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("reused for a different tenant or payload"); + + DemoTenantEntitlementRequest wrongSourceTenant = + request( + UUID.fromString("77777777-7777-4777-8777-777777777777"), + otherTenantId, + source, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> entitlements.provision(wrongSourceTenant, source))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining( + "Only exact authenticated fresh Game Design tenant creation evidence"); + + DemoTenantEntitlementRequest update = + request( + UUID.fromString("88888888-8888-4888-8888-888888888888"), + tenantId, + source, + first.entitlementVersion(), + first.tenantAuthorityGeneration(), + first.tenantAuthoritySourceVersion(), + false); + DemoTenantEntitlementSnapshot updated = + inTransaction(context.transaction(), () -> entitlements.provision(update, source)); + assertThat(updated.entitlementVersion()).isEqualTo(2L); + assertThat(updated.tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(updated.tenantAuthoritySourceVersion()).isEqualTo(3L); + assertThat(updated.tenantBillingSequence()).isEqualTo(2L); + assertThat(updated.tenantAuthorityOutboxSequence()).isEqualTo(2L); + assertThat(inTransaction(context.transaction(), () -> entitlements.provision(update, source))) + .isEqualTo(updated); + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> entitlements.revalidate(first))) + .isInstanceOf(DemoTenantEntitlementException.class) + .hasMessageContaining("changed after its complete evaluation snapshot"); + + Long legacyIdentityColumnCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = ? " + + "AND table_name = 'account_demo_tenant_entitlements' " + + "AND column_name IN ('tenant_id', 'legacy_tenant_id')", + context.schema()), + "Expected information_schema aggregate row") + .get(0, Long.class); + assertThat(legacyIdentityColumnCount).isZero(); + Long outboxEventCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement outbox aggregate row") + .get(0, Long.class); + assertThat(outboxEventCount).isEqualTo(2L); + Long authorityEventCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + tenantId), + "Expected tenant authority outbox aggregate row") + .get(0, Long.class); + assertThat(authorityEventCount).isEqualTo(2L); + Long operationCount = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement operation aggregate row") + .get(0, Long.class); + assertThat(operationCount).isEqualTo(2L); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'TENANT' " + + "AND tenant_uuid = ?", + tenantId); + return null; + })) + .isInstanceOf(RuntimeException.class); + assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) + .isEqualTo(updated); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_demo_tenant_entitlements SET gameplay_available = NOT gameplay_available " + + "WHERE tenant_uuid = ?", + tenantId); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Demo entitlement identity is immutable and version advances by one"); + assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) + .isEqualTo(updated); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> tenantAuthorityEvents.readCurrentByTenant(tenantId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from its exact committed billing event"); + } + + @Test + void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHistory() { + TestContext context = newTestContext(); + FreshTenantIdentityAssociationRepository identityRepository = + new FreshTenantIdentityAssociationRepository(context.dsl(), TEST_NAMESPACE); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(context.dsl()); + AccountTenantEntitlementOutboxRepository outboxRepository = + new AccountTenantEntitlementOutboxRepository(context.dsl()); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + context.dsl(), + new AccountAuthorityOutboxRepository(context.dsl()), + outboxRepository, + identityRepository, + generationRepository); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + context.dsl(), + identityRepository, + generationRepository, + outboxRepository, + tenantAuthorityEvents); + + UUID rollbackTenant = UUID.fromString("66666666-6666-4666-8666-666666666666"); + FreshTenantCreationEvidence rollbackSource = evidence(rollbackTenant, 803L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(rollbackSource); + generationRepository.initializeTenantIfAbsent(rollbackTenant); + return null; + }); + DemoTenantEntitlementRequest rollbackRequest = + request( + UUID.fromString("66666666-6666-4666-8666-666666666667"), + rollbackTenant, + rollbackSource, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + entitlements.provision(rollbackRequest, rollbackSource); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + assertTenantHasOnlyGenerationOne(context, rollbackTenant); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:tenant/" + rollbackTenant), + "Expected rolled-back tenant authority outbox aggregate row") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + rollbackTenant), + "Expected rolled-back tenant billing outbox aggregate row") + .get(0, Long.class)) + .isZero(); + + UUID retainedTenant = UUID.fromString("77777777-7777-4777-8777-777777777777"); + FreshTenantCreationEvidence retainedSource = evidence(retainedTenant, 804L); + inTransaction( + context.transaction(), + () -> { + identityRepository.importVerified(retainedSource); + return null; + }); + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('TENANT', NULL, NULL, ?, 2, 2)", + retainedTenant); + return null; + }); + DemoTenantEntitlementRequest retainedRequest = + request( + UUID.fromString("77777777-7777-4777-8777-777777777778"), + retainedTenant, + retainedSource, + null, + null, + null, + true); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> entitlements.provision(retainedRequest, retainedSource))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("advanced without canonical source-event evidence"); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + retainedTenant), + "Expected retained tenant authority generation row") + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ?", + retainedTenant), + "Expected retained tenant identity association aggregate row") + .get(0, Long.class)) + .isEqualTo(1L); + } + + private static void assertTenantHasOnlyGenerationOne(TestContext context, UUID tenantId) { + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantId), + "Expected tenant authority generation row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ?", + tenantId), + "Expected tenant entitlement operation aggregate row") + .get(0, Long.class)) + .isZero(); + } + + private TestContext newTestContext() { + String schema = "demo_entitlement_" + UUID.randomUUID().toString().replace("-", ""); + runOwnedSchemas.add(schema); + org.jooq + .impl + .DSL + .using(rootDataSource, SQLDialect.POSTGRES) + .execute("CREATE SCHEMA \"" + schema + "\""); + DriverManagerDataSource dataSource = postgresFixture.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dsl, new TransactionTemplate(new DataSourceTransactionManager(dataSource)), schema); + } + + private static DemoTenantEntitlementRequest request( + UUID requestId, + UUID tenantId, + FreshTenantCreationEvidence source, + Long entitlementVersion, + Long authorityGeneration, + Long authoritySourceVersion, + boolean gameplayAvailable) { + return new DemoTenantEntitlementRequest( + requestId, + tenantId, + source.creationRequestId(), + source.requestDigest(), + entitlementVersion, + authorityGeneration, + authoritySourceVersion, + gameplayAvailable, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } + + private static FreshTenantCreationEvidence evidence(UUID tenantId, long sourceRowId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String digest = "sha256:" + Long.toHexString(sourceRowId % 16L).repeat(64); + String sourceKey = "demo-source-" + sourceRowId; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + digest, + tenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + digest, + tenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static FreshTenantCreationEvidence alteredProvenance(FreshTenantCreationEvidence source) { + long sourceRowId = source.sourceGameRowId() + 1000L; + UUID operationId = UUID.randomUUID(); + String sourceKey = "different-source-" + sourceRowId; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + source.canonicalTenantId(), + sourceRowId, + sourceKey, + source.provenanceKind()); + return new FreshTenantCreationEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + operationId, + source.requestDigest(), + source.canonicalTenantId(), + sourceRowId, + sourceKey, + source.provenanceKind(), + evidenceDigest); + } + + private static T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier action) { + return transaction.execute(status -> action.get()); + } + + private record TestContext(DSLContext dsl, TransactionTemplate transaction, String schema) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index 0aaedf7407..07394bd20f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -5,6 +5,7 @@ import java.net.URI; import java.util.Properties; import net.firedevops.firemud.test.TestContainerImages; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.PostgreSQLContainer; @@ -15,21 +16,34 @@ public final class AccountPostgresIntegrationFixture { private final PostgreSQLContainer container; private final String externalJdbcUrl; + private final boolean requireDurablePrimary; private boolean started; public AccountPostgresIntegrationFixture() { + this(false); + } + + public AccountPostgresIntegrationFixture(boolean requireDurablePrimary) { + this.requireDurablePrimary = requireDurablePrimary; String configuredUrl = System.getenv(JDBC_URL_ENV); if (configuredUrl != null && !configuredUrl.isBlank()) { externalJdbcUrl = validateLoopbackJdbcUrl(configuredUrl); container = null; } else { externalJdbcUrl = null; - container = new PostgreSQLContainer<>(TestContainerImages.postgres()); + PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + if (requireDurablePrimary) { + postgres = postgres.withCommand(durablePostgresCommand()); + } + container = postgres; } } public void start() { if (container == null) { + if (requireDurablePrimary) { + verifyDurablePrimary(); + } return; } assumeTrue( @@ -37,6 +51,14 @@ public void start() { "Docker is unavailable; set " + JDBC_URL_ENV + " to an isolated loopback PostgreSQL URL"); container.start(); started = true; + if (requireDurablePrimary) { + try { + verifyDurablePrimary(); + } catch (RuntimeException unsuitable) { + stop(); + throw unsuitable; + } + } } public void stop() { @@ -91,6 +113,45 @@ public DriverManagerDataSource dataSource(String schema) { return dataSource; } + /** Reads and validates the live PostgreSQL settings required by durable commit confirmation. */ + public DurablePrimarySettings verifyDurablePrimary() { + DurablePrimarySettings settings = + new JdbcTemplate(dataSource()) + .queryForObject( + "SELECT pg_is_in_recovery(), current_setting('fsync'), " + + "current_setting('synchronous_commit')", + (result, rowNumber) -> + new DurablePrimarySettings( + result.getBoolean(1), result.getString(2), result.getString(3))); + if (settings == null) { + throw new IllegalStateException("Durable PostgreSQL primary settings are unavailable"); + } + validateDurablePrimarySettings( + settings.inRecovery(), settings.fsync(), settings.synchronousCommit()); + return settings; + } + + static String[] durablePostgresCommand() { + return new String[] {"postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"}; + } + + static void validateDurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) { + if (inRecovery || !"on".equals(fsync) || !"on".equals(synchronousCommit)) { + throw new IllegalStateException( + "Durable PostgreSQL primary required (pg_is_in_recovery=false, fsync=on, " + + "synchronous_commit=on); observed pg_is_in_recovery=" + + inRecovery + + ", fsync=" + + fsync + + ", synchronous_commit=" + + synchronousCommit); + } + } + + public record DurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) {} + static String validateLoopbackJdbcUrl(String jdbcUrl) { final URI uri; try { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java new file mode 100644 index 0000000000..f5c95ce65e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java @@ -0,0 +1,472 @@ +package integration.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** PostgreSQL regression proof for current, non-admitting Account actor-staging evidence. */ +class AccountActorStagingEligibilityPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "actor_staging_eligibility_"; + private static final String TEST_NAMESPACE = "actor-staging-eligibility-proof"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private final Set runOwnedSchemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + postgres.start(); + } + + @AfterAll + static void stopPostgres() { + postgres.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate rootJdbc = new JdbcTemplate(postgres.dataSource()); + for (String schema : runOwnedSchemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + rootJdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @Test + void requiresCurrentMembershipEventAndReturnsBoundStagingOnlyEvidence() { + Fixture fixture = newFixture(); + UUID stagingRequestId = UUID.randomUUID(); + + assertThatThrownBy(() -> fixture.resolveStaging(stagingRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current positive Account membership is absent"); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isZero(); + assertThat(fixture.retainedMembershipEventCount()).isZero(); + + fixture.createAndPublishMembershipEvent(); + AccountActorStagingEligibilityEvidence evidence = fixture.resolveStaging(stagingRequestId); + PairAuthority pair = fixture.readPositivePair(); + AccountAuthorityOutboxRepository.Event event = fixture.readCurrentMembershipEvent(pair); + MembershipEvent decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + DemoTenantEntitlementSnapshot entitlement = fixture.readCurrentEntitlement(); + + assertThat(entitlement.status()).isEqualTo("ACTIVE"); + assertThat(entitlement.gameplayAvailable()).isTrue(); + assertThat(entitlement.allowPublicJoin()).isTrue(); + assertThat(entitlement.tenantBillingSequence()).isPositive(); + assertThat(entitlement.tenantAuthorityOutboxSequence()).isPositive(); + + assertThat(evidence.schemaVersion()) + .isEqualTo(AccountActorStagingEligibilityEvidence.SCHEMA_VERSION); + assertThat(evidence.targetNamespace()).isEqualTo(TEST_NAMESPACE); + assertThat(evidence.requestId()).isEqualTo(stagingRequestId); + assertThat(evidence.canonicalAccountId()).isEqualTo(fixture.account.getAccountUuid()); + assertThat(evidence.canonicalTenantId()).isEqualTo(fixture.tenantUuid); + assertThat(evidence.purpose()).isEqualTo(Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE); + assertThat(evidence.observedAt()).isNotNull(); + assertThat(evidence.accountUuidProvenance()) + .isEqualTo(fixture.account.getAccountUuidProvenance().name()); + assertThat(evidence.accountLifecycleState()).isEqualTo("ACTIVE"); + assertThat(evidence.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(evidence.gameplayAdmissionAllowed()).isTrue(); + assertThat(evidence.membershipAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); + assertThat(evidence.membershipVersion()).isEqualTo(pair.membershipVersion()); + assertThat(evidence.membershipAuthorityGeneration()) + .isEqualTo(pair.membershipAuthorityGeneration()); + assertThat(evidence.membershipEventSequence()).isEqualTo(pair.eventSequence()); + assertThat(evidence.membershipEventId().toString()).isEqualTo(pair.eventId()); + assertThat(evidence.membershipEventDigest()).isEqualTo(pair.eventDigest()); + assertThat(evidence.lastTransitionInvalidated()).isFalse(); + assertThat(evidence.tenantProvenanceKind()).isEqualTo("FRESH_GAME_DESIGN"); + assertThat(evidence.tenantSourceOperationId()).isEqualTo(fixture.tenantEvidence.operationId()); + assertThat(evidence.tenantProvenanceDigest()) + .isEqualTo(fixture.tenantEvidence.evidenceDigest()); + assertThat(event.outboxStreamKey()).isEqualTo(fixture.membershipStream()); + assertThat(event.requestId()).isEqualTo(fixture.joinRequestId); + assertThat(decoded.requestId()).isEqualTo(fixture.joinRequestId); + assertThat(decoded.accountId()).isEqualTo(fixture.account.getAccountUuid().toString()); + assertThat(decoded.tenantId()).isEqualTo(fixture.tenantUuid.toString()); + assertThat(decoded.membershipVersion()).containsEntry(fixture.tenantUuid.toString(), "2"); + assertThat(decoded.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(decoded.eventId()).isEqualTo(pair.eventId()); + assertThat(decoded.eventDigest()).isEqualTo(pair.eventDigest()); + + AccountActorStagingEligibilityEvidence secondRequestEvidence = + fixture.resolveStaging(UUID.randomUUID()); + assertThat(secondRequestEvidence.requestId()).isNotEqualTo(evidence.requestId()); + assertThat(fixture.readCurrentEntitlement()).isEqualTo(entitlement); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isEqualTo(1L); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.retainedMembershipEventCount()).isEqualTo(1L); + assertThat(fixture.currentMembershipCheckpointSequence()).isEqualTo(pair.eventSequence()); + assertThat(fixture.maximumRetainedMembershipEventSequence()).isEqualTo(pair.eventSequence()); + assertThat(fixture.joinOperationStatus()).isEqualTo("PENDING"); + } + + private Fixture newFixture() { + return new Fixture(newTestContext()); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + runOwnedSchemas.add(schema); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + TransactionTemplate readOnlySnapshot = new TransactionTemplate(transactionManager); + readOnlySnapshot.setReadOnly(true); + readOnlySnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + return new TestContext(dsl, transaction, readOnlySnapshot); + } + + private static final class Fixture { + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final TransactionTemplate readOnlySnapshot; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final FreshTenantIdentityAssociationRepository freshTenants; + private final AccountDemoTenantEntitlementRepository entitlements; + private final AccountRepository accounts; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRepository memberships; + private final AccountTenantMembershipRoleSnapshotRepository roles; + private final AccountConnectScopeRepository connectScopes; + private final AccountJoinOperationRepository joinOperations; + private final AccountMembershipAuthorityEventProducer membershipEvents; + private final Account account; + private final UUID tenantUuid = UUID.randomUUID(); + private final FreshTenantCreationEvidence tenantEvidence; + private final VerifiedTenantProvenance tenantProvenance; + private final CanonicalJoinScopeV2 scope; + private final String joinRequestId = UUID.randomUUID().toString(); + private final String callerBinding = "actor-staging-caller-" + UUID.randomUUID(); + + private Fixture(TestContext context) { + this.dsl = context.dsl(); + this.transaction = context.transaction(); + this.readOnlySnapshot = context.readOnlySnapshot(); + this.generations = new AccountAuthorityGenerationRepository(dsl); + this.outbox = new AccountAuthorityOutboxRepository(dsl); + this.sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + this.freshTenants = new FreshTenantIdentityAssociationRepository(dsl, TEST_NAMESPACE); + var billingOutbox = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + this.entitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantEvents); + this.accounts = new AccountRepository(dsl, sourceEvidence); + this.pairs = new AccountMembershipPairAuthorityRepository(dsl); + this.memberships = new AccountTenantMembershipRepository(dsl, accounts, freshTenants, pairs); + this.roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + this.tenantEvidence = freshTenantEvidence(tenantUuid); + this.tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + seedTenantAndActiveEntitlement(); + this.account = createAccount(); + this.scope = canonicalScope(account.getAccountUuid(), tenantUuid); + + var retainedIdentityResolver = + new AccountTenantIdentityResolver( + new ApprovedLegacyTenantAssociationRepository( + dsl, new LegacyTenantSourceEvidence(dsl), TEST_NAMESPACE), + TEST_NAMESPACE); + this.connectScopes = + new AccountConnectScopeRepository(dsl, retainedIdentityResolver, freshTenants); + this.joinOperations = new AccountJoinOperationRepository(dsl, connectScopes); + this.membershipEvents = + new AccountMembershipAuthorityEventProducer( + joinOperations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sourceEvidence); + seedMembershipOperation(); + } + + private void seedTenantAndActiveEntitlement() { + transaction.executeWithoutResult( + status -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + }); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + transaction.executeWithoutResult(status -> entitlements.provision(request, tenantEvidence)); + } + + private Account createAccount() { + Account input = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + input.setUsername("actor-staging-" + suffix); + input.setEmail("actor-staging-" + suffix + "@example.test"); + input.setPasswordHash("integration-fixture-hash"); + input.setRole("player"); + return transaction.execute(status -> accounts.save(input)); + } + + private void seedMembershipOperation() { + transaction.executeWithoutResult( + status -> { + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), scope, tenantProvenance); + joinOperations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + joinOperations.bindCanonicalPolicyEvidence( + joinRequestId, scope, callerBinding, true, 5L); + }); + } + + private void createAndPublishMembershipEvent() { + transaction.executeWithoutResult( + status -> { + var membership = + memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + roles.replaceCanonical( + membership, + account.getAccountUuid(), + tenantUuid, + tenantProvenance, + 2L, + java.util.List.of("player")); + membershipEvents.publishCanonicalFirstJoinMembershipChange( + scope, joinRequestId, callerBinding); + }); + } + + private AccountActorStagingEligibilityEvidence resolveStaging(UUID requestId) { + AccountActorStagingEligibilityRepository sourceRepository = + new AccountActorStagingEligibilityRepository( + dsl, accounts, freshTenants, memberships, pairs); + AccountActorStagingEligibilityService service = + new AccountActorStagingEligibilityService(sourceRepository, TEST_NAMESPACE); + return readOnlySnapshot.execute( + status -> + service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + TEST_NAMESPACE, + requestId, + account.getAccountUuid(), + tenantUuid, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)); + } + + private PairAuthority readPositivePair() { + return transaction.execute( + status -> pairs.readPositive(account.getAccountUuid(), tenantUuid).orElseThrow()); + } + + private AccountAuthorityOutboxRepository.Event readCurrentMembershipEvent(PairAuthority pair) { + String stream = membershipStream(); + return transaction.execute( + status -> outbox.findEvent(stream, pair.eventSequence()).orElseThrow()); + } + + private DemoTenantEntitlementSnapshot readCurrentEntitlement() { + return transaction.execute(status -> entitlements.readCurrent(tenantUuid)); + } + + private long retainedMembershipEventCount() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + membershipStream())) + .get(0, Long.class); + } + + private long currentMembershipCheckpointSequence() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + membershipStream())) + .get(0, Long.class); + } + + private long maximumRetainedMembershipEventSequence() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT max(outbox_sequence) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + membershipStream())) + .get(0, Long.class); + } + + private String joinOperationStatus() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM account_join_operations WHERE request_id = ?", joinRequestId)) + .get(0, String.class); + } + + private long count(String table, String keyColumn, Object value) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM " + table + " WHERE " + keyColumn + " = ?", value)) + .get(0, Long.class); + } + + private String membershipStream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account.getAccountUuid() + + "/" + + tenantUuid; + } + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "actor-staging-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Actor staging eligibility test", null); + long sourceGameRowId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + if (sourceGameRowId == 0L) { + sourceGameRowId = 1L; + } + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private static CanonicalJoinScopeV2 canonicalScope(UUID accountUuid, UUID tenantUuid) { + return new CanonicalJoinScopeV2( + "actor-staging-scope-" + UUID.randomUUID().toString().replace("-", ""), + accountUuid, + tenantUuid, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7L, + 3L, + java.time.Instant.now().toString(), + java.time.Instant.now().plusSeconds(120L).toString()); + } + + private record TestContext( + DSLContext dsl, TransactionTemplate transaction, TransactionTemplate readOnlySnapshot) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java new file mode 100644 index 0000000000..2135a89085 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java @@ -0,0 +1,207 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class DemoTenantEntitlementCodecTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID CREATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String CREATION_DIGEST = "sha256:" + "a".repeat(64); + private static final long TWO_TO_53 = 9_007_199_254_740_992L; + private static final long TWO_TO_53_PLUS_ONE = 9_007_199_254_740_993L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void requestDigestDistinguishesAdjacentValuesAboveIeeeIntegerPrecision() { + String exactRequestValue = request(TWO_TO_53_PLUS_ONE, TWO_TO_53).requestDigest(); + String roundedRequestValue = request(TWO_TO_53, TWO_TO_53).requestDigest(); + String exactQuotaValue = request(TWO_TO_53, TWO_TO_53_PLUS_ONE).requestDigest(); + String roundedQuotaValue = request(TWO_TO_53, TWO_TO_53).requestDigest(); + + assertThat(exactRequestValue).isNotEqualTo(roundedRequestValue); + assertThat(exactQuotaValue).isNotEqualTo(roundedQuotaValue); + } + + @Test + void eventRoundTripPreservesLongMaxAndValuesAboveIeeeIntegerPrecisionAsDecimalStrings() { + DemoTenantEntitlementRequest request = + request( + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE, + new DemoTenantEntitlementRequest.Quotas( + Long.MAX_VALUE, TWO_TO_53_PLUS_ONE, Long.MAX_VALUE)); + FreshTenantCreationEvidence source = source(TWO_TO_53_PLUS_ONE); + DemoTenantEntitlementEventV1Codec.Event sealed = + DemoTenantEntitlementEventV1Codec.seal( + request, + source, + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE, + Long.MAX_VALUE, + TWO_TO_53_PLUS_ONE); + + DemoTenantEntitlementEventV1Codec.Event verified = + DemoTenantEntitlementEventV1Codec.verify(sealed.payload()); + String payload = new String(sealed.payload(), StandardCharsets.UTF_8); + + assertThat(verified.entitlementVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(verified.tenantAuthorityGeneration()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.tenantAuthoritySourceVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(verified.tenantBillingSequence()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.sourceEvidence().sourceGameRowId()).isEqualTo(TWO_TO_53_PLUS_ONE); + assertThat(verified.quotas()) + .isEqualTo( + new DemoTenantEntitlementRequest.Quotas( + Long.MAX_VALUE, TWO_TO_53_PLUS_ONE, Long.MAX_VALUE)); + assertThat(payload) + .contains("\"entitlementVersion\":\"9223372036854775807\"") + .contains("\"tenantAuthorityGeneration\":\"9007199254740993\"") + .contains("\"tenantBillingSequence\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740993\"") + .contains("\"maxConcurrentGameInstances\":\"9007199254740993\"") + .contains("\"schemaVersion\":1"); + } + + @Test + void eventVerifierRejectsNoncanonicalLongRepresentations() throws Exception { + byte[] validPayload = event().payload(); + + assertInvalidCounter(validPayload, 1); + assertInvalidCounter(validPayload, "01"); + assertInvalidCounter(validPayload, "1e2"); + assertInvalidCounter(validPayload, "1.0"); + assertInvalidCounter(validPayload, "9223372036854775808"); + assertInvalidQuota(validPayload, "01"); + assertInvalidQuota(validPayload, "-1"); + } + + @Test + void eventVerifierRejectsDuplicateKeysAndTrailingInput() throws Exception { + byte[] validPayload = event().payload(); + String canonical = new String(validPayload, StandardCharsets.UTF_8); + String duplicateKey = + canonical.replace( + "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\"", + "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\",\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\""); + + assertThatThrownBy( + () -> + DemoTenantEntitlementEventV1Codec.verify( + duplicateKey.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + DemoTenantEntitlementEventV1Codec.verify( + (canonical + " {}").getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidCounter(byte[] validPayload, Object invalidValue) + throws Exception { + Map wire = readWire(validPayload); + wire.put("tenantBillingSequence", invalidValue); + assertThatThrownBy(() -> DemoTenantEntitlementEventV1Codec.verify(resign(wire))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidQuota(byte[] validPayload, Object invalidValue) + throws Exception { + Map wire = readWire(validPayload); + nestedObject(wire, "quotas").put("maxStorageBytes", invalidValue); + assertThatThrownBy(() -> DemoTenantEntitlementEventV1Codec.verify(resign(wire))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DemoTenantEntitlementEventV1Codec.Event event() { + return DemoTenantEntitlementEventV1Codec.seal(request(1L, 1L), source(91L), 1L, 1L, 1L, 1L); + } + + private static DemoTenantEntitlementRequest request(long expectedVersion, long quotaValue) { + return request( + expectedVersion, + expectedVersion, + new DemoTenantEntitlementRequest.Quotas(quotaValue, quotaValue, quotaValue)); + } + + private static DemoTenantEntitlementRequest request( + long expectedVersion, + long expectedSourceVersion, + DemoTenantEntitlementRequest.Quotas quotas) { + return new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + CREATION_ID, + CREATION_DIGEST, + expectedVersion, + expectedVersion, + expectedSourceVersion, + true, + false, + true, + true, + quotas); + } + + private static FreshTenantCreationEvidence source(long sourceGameRowId) { + String tenantKey = "demo-tenant-source-key"; + return new FreshTenantCreationEvidence( + 1, + "account-service", + CREATION_ID, + OPERATION_ID, + CREATION_DIGEST, + TENANT_ID, + sourceGameRowId, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "account-service", + CREATION_ID, + OPERATION_ID, + CREATION_DIGEST, + TENANT_ID, + sourceGameRowId, + tenantKey, + "NEW_GAME_ROW")); + } + + private static Map readWire(byte[] payload) throws IOException { + return JSON.readValue(payload, new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map nestedObject(Map wire, String field) { + return (Map) wire.get(field); + } + + private static byte[] resign(Map wire) throws Exception { + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + String digest = + "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalPreimage)); + preimage.put("eventDigest", digest); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..e783f4c871 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java @@ -0,0 +1,88 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +class TenantAuthorityEventV1CodecTest { + @Test + void authorityEventKeepsItsCanonicalCheckpointSeparateFromBillingReceipt() { + UUID tenantId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + FreshTenantCreationEvidence source = source(tenantId); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + tenantId, + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + TenantAuthorityEventV1Codec.Event authorityEvent = + TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billingEvent); + + TenantAuthorityEventV1Codec.Event verified = + TenantAuthorityEventV1Codec.verify(authorityEvent.payload()); + assertThat(verified.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantId); + assertThat(verified.outboxSequence()).isEqualTo(1L); + assertThat(verified.tenantBillingStreamKey()) + .isEqualTo("account:tenant-entitlement:v1:tenant/" + tenantId); + assertThat(verified.tenantBillingSequence()).isEqualTo(1L); + assertThat(verified.eventId()) + .isEqualTo(TenantAuthorityEventV1Codec.eventId(request.requestId())); + assertThat(verified.tenantBillingEventId()).isEqualTo(billingEvent.eventId()); + assertThat(verified.tenantBillingEventDigest()).isEqualTo(billingEvent.eventDigest()); + assertThat(verified.sourceEvidence()).isEqualTo(source); + assertThat(new String(verified.payload(), StandardCharsets.UTF_8)) + .contains("\"tenantAuthorityGeneration\":\"2\"") + .contains("\"tenantBillingSequence\":\"1\""); + + byte[] altered = authorityEvent.payload(); + altered[altered.length - 2] = altered[altered.length - 2] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> TenantAuthorityEventV1Codec.verify(altered)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreationEvidence source(UUID tenantId) { + UUID creationRequestId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID operationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String requestDigest = "sha256:" + "a".repeat(64); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + "account-service", + creationRequestId, + operationId, + requestDigest, + tenantId, + 801L, + "tenant-801", + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + "account-service", + creationRequestId, + operationId, + requestDigest, + tenantId, + 801L, + "tenant-801", + "NEW_GAME_ROW", + evidenceDigest); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java new file mode 100644 index 0000000000..bd2a21e841 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -0,0 +1,147 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantAuthorityEventRepositoryTest { + private static final String NAMESPACE = "prod"; + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String SOURCE_REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void appendBindsBillingEventIdAsUuidAndAuthorityEventIdAsVarcharText() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthorityOutboxRepository authorityOutbox = mock(AccountAuthorityOutboxRepository.class); + AccountTenantEntitlementOutboxRepository billingOutbox = + mock(AccountTenantEntitlementOutboxRepository.class); + FreshTenantIdentityAssociationRepository tenantIdentity = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + Record sourceHead = mock(Record.class); + when(sourceHead.get("current_generation", Long.class)).thenReturn(1L); + when(sourceHead.get("current_source_version", Long.class)).thenReturn(1L); + when(sourceHead.get("last_outbox_sequence", Long.class)).thenReturn(0L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(sourceHead); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + + FreshTenantCreationEvidence source = freshTenantEvidence(); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + SOURCE_REQUEST_ID, + SOURCE_REQUEST_DIGEST, + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + ScopeState nextAuthority = new ScopeState(AuthorityScope.tenant(TENANT_ID), 2L, 2L, null); + String streamKey = TenantAuthorityEventV1Codec.streamKey(TENANT_ID); + + doAnswer( + invocation -> { + LongFunction evidenceFactory = + invocation.getArgument(2); + AccountAuthorityOutboxRepository.EventEvidence evidence = evidenceFactory.apply(1L); + return new AccountAuthorityOutboxRepository.Event( + streamKey, + REQUEST_ID.toString(), + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + }) + .when(authorityOutbox) + .append(eq(streamKey), eq(REQUEST_ID.toString()), any()); + + AccountTenantAuthorityEventRepository repository = + new AccountTenantAuthorityEventRepository( + dsl, authorityOutbox, billingOutbox, tenantIdentity, generations); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TenantAuthorityEventV1Codec.Event appended = + repository.append(request, source, nextAuthority, billingEvent); + + assertThat(appended.tenantBillingEventId()).isEqualTo(billingEvent.eventId()); + assertThat(TenantAuthorityEventV1Codec.verify(appended.payload()).tenantBillingEventId()) + .isEqualTo(billingEvent.eventId()); + + ArgumentCaptor updateSql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor updateBindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(updateSql.capture(), updateBindings.capture()); + assertThat(updateSql.getValue()) + .contains("tenant_billing_sequence = ?, tenant_billing_event_id = ?"); + Object[] bindings = updateBindings.getValue(); + assertThat(bindings).hasSize(14); + assertThat(bindings[5]) + .isExactlyInstanceOf(String.class) + .isEqualTo(appended.eventId().toString()); + assertThat(bindings[8]).isExactlyInstanceOf(UUID.class).isEqualTo(billingEvent.eventId()); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private static FreshTenantCreationEvidence freshTenantEvidence() { + String sourceTenantKey = "tenant-source-44444444"; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java new file mode 100644 index 0000000000..7706831a7d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java @@ -0,0 +1,143 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository; +import net.firedevops.firemud.accountservice.repository.AccountActorStagingEligibilityRepository.CurrentSnapshot; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import org.junit.jupiter.api.Test; + +class AccountActorStagingEligibilityServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID ACCOUNT_UUID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TENANT_UUID = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); + private static final UUID REQUEST_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_UUID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID EVENT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + private final AccountActorStagingEligibilityRepository repository = + mock(AccountActorStagingEligibilityRepository.class); + private final AccountActorStagingEligibilityService service = + new AccountActorStagingEligibilityService(repository, NAMESPACE); + + @Test + void sealsEligibleEvidenceOnlyFromTheRequestedOwnerSnapshot() { + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)).thenReturn(snapshot("ACTIVE", true)); + + AccountActorStagingEligibilityEvidence evidence = + service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + + assertThat(evidence.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.membershipVersion()).isEqualTo(2L); + assertThat(evidence.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(evidence.membershipEventSequence()).isEqualTo(1L); + assertThat(evidence.membershipEventId()).isEqualTo(EVENT_UUID); + assertThat(evidence.membershipEventDigest()).startsWith("sha256:"); + assertThat(evidence.tenantSourceOperationId()).isEqualTo(SOURCE_OPERATION_UUID); + assertThat(evidence.tenantProvenanceDigest()).startsWith("sha256:"); + assertThat(evidence.authoritySnapshotDigest()).hasSize(64); + assertThat(evidence.eligibilityDecisionDigest()).hasSize(64); + verify(repository).readCurrent(ACCOUNT_UUID, TENANT_UUID); + } + + @Test + void currentButInactiveOrAdmissionBlockedSourcesProduceIneligibleStagingEvidence() { + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(snapshot("SECURITY_LOCKED", true)); + + AccountActorStagingEligibilityEvidence lockedAccount = resolve(); + + assertThat(lockedAccount.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)).thenReturn(snapshot("ACTIVE", false)); + + AccountActorStagingEligibilityEvidence blockedMembership = resolve(); + + assertThat(blockedMembership.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + } + + @Test + void rejectsUnsupportedScopeAndPurposeBeforeReadingOwnerSources() { + assertThatThrownBy( + () -> + service.resolve( + 2, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.resolve( + 1, + "other", + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.resolve( + 1, + NAMESPACE, + new UUID(0L, 0L), + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository); + } + + private AccountActorStagingEligibilityEvidence resolve() { + return service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + } + + private static CurrentSnapshot snapshot(String lifecycle, boolean admissionAllowed) { + return new CurrentSnapshot( + ACCOUNT_UUID, + AccountIdentityProvenance.ACCOUNT_V29_MIGRATION, + lifecycle, + TENANT_UUID, + "FRESH_GAME_DESIGN", + SOURCE_OPERATION_UUID, + "sha256:" + "a".repeat(64), + "ACTIVE", + admissionAllowed, + "EXPLICIT_JOIN", + 2L, + 1L, + 1L, + EVENT_UUID, + "sha256:" + "b".repeat(64), + false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java new file mode 100644 index 0000000000..3ca207bfff --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java @@ -0,0 +1,251 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityPurpose; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityRequest; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityResponse; +import net.firedevops.firemud.accountservice.service.AccountActorStagingEligibilityService; +import net.firedevops.firemud.accountservice.service.impl.AccountActorStagingEligibilityGrpcService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.io.FileSystemResource; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.util.StreamUtils; + +class AccountActorStagingEligibilityGrpcServiceTest { + private static final String AUTH_METHOD = + "account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility"; + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID ACCOUNT_UUID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TENANT_UUID = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); + private static final UUID REQUEST_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_UUID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID EVENT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + private final AccountActorStagingEligibilityService ownerService = + mock(AccountActorStagingEligibilityService.class); + private final AccountActorStagingEligibilityGrpcService service = + new AccountActorStagingEligibilityGrpcService(ownerService, NAMESPACE); + + @Test + void grpcRegistrationIsOptInAndTheExactMethodHasMtlSHandlerCoverage() throws IOException { + ConditionalOnProperty condition = + AccountActorStagingEligibilityGrpcService.class.getAnnotation(ConditionalOnProperty.class); + assertThat(condition).isNotNull(); + assertThat(condition.prefix()).isEqualTo("firemud.account.actor-staging-eligibility"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()).isFalse(); + + String baseConfiguration = resource("application.yml"); + String productionConfiguration = resource("application-prod.yml"); + assertThat(baseConfiguration) + .contains("enabled: ${FIREMUD_ACCOUNT_ACTOR_STAGING_ELIGIBILITY_ENABLED:false}") + .contains("- " + AUTH_METHOD); + assertThat(productionConfiguration).contains("- " + AUTH_METHOD); + } + + @Test + void returnsExactStagingOnlySnapshotToSameNamespaceEntityPeer() { + AccountActorStagingEligibilityEvidence evidence = evidence(); + when(ownerService.resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .thenReturn(evidence); + + TestObserver observer = call(request(), ENTITY_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + ResolvePreseededActorStagingEligibilityResponse response = observer.value; + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getRequestId()).isEqualTo(REQUEST_UUID.toString()); + assertThat(response.getCanonicalAccountId()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_UUID.toString()); + assertThat(response.getPurpose()) + .isEqualTo(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY); + assertThat(response.getCurrentness().name()).isEqualTo("CURRENT_AT_REVALIDATION"); + assertThat(response.getDecision().name()).isEqualTo("STAGING_ELIGIBLE"); + assertThat(response.getMembershipVersion()).isEqualTo(2L); + assertThat(response.getMembershipEventSequence()).isEqualTo(1L); + assertThat(response.getMembershipEventId()).isEqualTo(EVENT_UUID.toString()); + assertThat(response.getTenantSourceOperationId()).isEqualTo(SOURCE_OPERATION_UUID.toString()); + assertThat(response.getAuthoritySnapshotDigest()).isEqualTo(evidence.authoritySnapshotDigest()); + verify(ownerService) + .resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY); + } + + @Test + void deniesNonEntityOrWrongNamespacePeersBeforeReadingAccountSources() { + assertThat(status(call(request(), null))).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(status(call(request(), "spiffe://firemud/ns/other/sa/entity-management-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(status(call(request(), "spiffe://firemud/ns/test/sa/game-session-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(status(call(request(), "spiffe://firemud/ns/test/sa/account-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerService); + } + + @Test + void rejectsOpenOrUnsupportedRequestsBeforeReadingAccountSources() { + ResolvePreseededActorStagingEligibilityRequest unknownField = + request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + ResolvePreseededActorStagingEligibilityRequest unsupportedPurpose = + request().toBuilder() + .setPurpose( + ActorStagingEligibilityPurpose.ACTOR_STAGING_ELIGIBILITY_PURPOSE_UNSPECIFIED) + .build(); + ResolvePreseededActorStagingEligibilityRequest unsupportedSchema = + request().toBuilder().setSchemaVersion(2).build(); + ResolvePreseededActorStagingEligibilityRequest wrongNamespace = + request().toBuilder().setTargetNamespace("other").build(); + + assertThat(status(call(unknownField, ENTITY_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(unsupportedPurpose, ENTITY_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(unsupportedSchema, ENTITY_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(call(wrongNamespace, ENTITY_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + call(request().toBuilder().setCanonicalTenantId("not-a-uuid").build(), ENTITY_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(ownerService); + } + + @Test + void distinguishesMissingCurrentEvidenceFromTemporarySourceFailure() { + when(ownerService.resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .thenThrow(new IllegalStateException("private Account source detail")) + .thenThrow(new DataAccessResourceFailureException("private database endpoint")); + + TestObserver missing = call(request(), ENTITY_URI); + TestObserver unavailable = call(request(), ENTITY_URI); + + assertThat(status(missing)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(missing.failure.getDescription()) + .isEqualTo("Current Account membership evidence is absent or contradictory"); + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + } + + private TestObserver call( + ResolvePreseededActorStagingEligibilityRequest request, String peerUri) { + TestObserver observer = new TestObserver(); + Runnable invocation = () -> service.resolvePreseededActorStagingEligibility(request, observer); + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static ResolvePreseededActorStagingEligibilityRequest request() { + return ResolvePreseededActorStagingEligibilityRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_UUID.toString()) + .setCanonicalAccountId(ACCOUNT_UUID.toString()) + .setCanonicalTenantId(TENANT_UUID.toString()) + .setPurpose(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) + .build(); + } + + private static AccountActorStagingEligibilityEvidence evidence() { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-08T00:00:00Z"), + "ACCOUNT_V29_MIGRATION", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 2L, + 1L, + "FRESH_GAME_DESIGN", + SOURCE_OPERATION_UUID, + "sha256:" + "a".repeat(64), + 1L, + EVENT_UUID, + "sha256:" + "b".repeat(64), + false); + } + + private static String resource(String name) throws IOException { + try (var input = new FileSystemResource("src/main/resources/" + name).getInputStream()) { + return StreamUtils.copyToString(input, StandardCharsets.UTF_8); + } + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.failure).isNotNull(); + return observer.failure.getCode(); + } + + private static final class TestObserver + implements StreamObserver { + private ResolvePreseededActorStagingEligibilityResponse value; + private Status failure; + private boolean completed; + + @Override + public void onNext(ResolvePreseededActorStagingEligibilityResponse response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java new file mode 100644 index 0000000000..5612ea1d2b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidence.java @@ -0,0 +1,434 @@ +package net.firedevops.firemud.common.account; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable, non-admitting Account evidence for public-production preseeded actor staging. */ +public record AccountActorStagingEligibilityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + UUID canonicalTenantId, + Purpose purpose, + Currentness currentness, + Instant observedAt, + Decision decision, + String accountUuidProvenance, + String accountLifecycleState, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated, + String eligibilityDecisionDigest, + String authoritySnapshotDigest) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern BARE_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SOURCE_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final List ACCOUNT_PROVENANCES = + List.of("ACCOUNT_V29_MIGRATION", "ACCOUNT_REPOSITORY_INSERT", "ACCOUNT_DATABASE_INSERT"); + private static final List ACCOUNT_LIFECYCLE_STATES = + List.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"); + + public AccountActorStagingEligibilityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported actor-staging evidence schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalAccountId, "canonicalAccountId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(tenantSourceOperationId, "tenantSourceOperationId"); + requireNonNil(membershipEventId, "membershipEventId"); + if (purpose != Purpose.PUBLIC_PRODUCTION_STAGING_ONLY) { + throw new IllegalArgumentException("Only public-production staging purpose is supported"); + } + if (currentness != Currentness.CURRENT_AT_REVALIDATION) { + throw new IllegalArgumentException("Current Account snapshot evidence is required"); + } + Objects.requireNonNull(observedAt, "observedAt is required"); + Objects.requireNonNull(decision, "decision is required"); + Objects.requireNonNull(accountUuidProvenance, "Account UUID provenance is required"); + Objects.requireNonNull(accountLifecycleState, "Account lifecycle state is required"); + Objects.requireNonNull(membershipLifecycleState, "membership lifecycle state is required"); + Objects.requireNonNull( + membershipAuthorityProvenance, "membership authority provenance is required"); + Objects.requireNonNull(tenantProvenanceKind, "tenant provenance kind is required"); + Objects.requireNonNull(tenantProvenanceDigest, "tenant provenance digest is required"); + Objects.requireNonNull(membershipEventDigest, "membership event digest is required"); + Objects.requireNonNull(eligibilityDecisionDigest, "eligibility decision digest is required"); + Objects.requireNonNull(authoritySnapshotDigest, "authority snapshot digest is required"); + requireMember(accountUuidProvenance, ACCOUNT_PROVENANCES, "Account UUID provenance"); + requireMember(accountLifecycleState, ACCOUNT_LIFECYCLE_STATES, "Account lifecycle state"); + if (!"ACTIVE".equals(membershipLifecycleState) + && !"INACTIVE".equals(membershipLifecycleState)) { + throw new IllegalArgumentException("Membership lifecycle state is not recognized"); + } + if (!"EXPLICIT_JOIN".equals(membershipAuthorityProvenance)) { + throw new IllegalArgumentException( + "Membership authority provenance is not current JOIN evidence"); + } + if (membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L + || membershipEventSequence <= 0L) { + throw new IllegalArgumentException("Positive membership authority counters are required"); + } + if (!"FRESH_GAME_DESIGN".equals(tenantProvenanceKind)) { + throw new IllegalArgumentException("Fresh canonical tenant provenance is required"); + } + requireDigest(tenantProvenanceDigest, SOURCE_SHA256, "tenant provenance digest"); + requireDigest(membershipEventDigest, SOURCE_SHA256, "membership event digest"); + requireDigest(eligibilityDecisionDigest, BARE_SHA256, "eligibility decision digest"); + requireDigest(authoritySnapshotDigest, BARE_SHA256, "authority snapshot digest"); + requireStrictUtf8(targetNamespace, "target namespace"); + requireStrictUtf8(accountUuidProvenance, "Account UUID provenance"); + requireStrictUtf8(accountLifecycleState, "Account lifecycle state"); + requireStrictUtf8(membershipLifecycleState, "membership lifecycle state"); + requireStrictUtf8(membershipAuthorityProvenance, "membership authority provenance"); + requireStrictUtf8(tenantProvenanceKind, "tenant provenance kind"); + requireStrictUtf8(tenantProvenanceDigest, "tenant provenance digest"); + requireStrictUtf8(membershipEventDigest, "membership event digest"); + + Decision expectedDecision = + "ACTIVE".equals(accountLifecycleState) + && "ACTIVE".equals(membershipLifecycleState) + && gameplayAdmissionAllowed + ? Decision.STAGING_ELIGIBLE + : Decision.STAGING_INELIGIBLE; + if (decision != expectedDecision) { + throw new IllegalArgumentException("Decision does not match the current Account snapshot"); + } + String expectedAuthorityDigest = + authoritySnapshotDigestFor( + fields( + schemaVersion, + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + currentness, + observedAt, + decision, + accountUuidProvenance, + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipAuthorityProvenance, + membershipVersion, + membershipAuthorityGeneration, + tenantProvenanceKind, + tenantSourceOperationId, + tenantProvenanceDigest, + membershipEventSequence, + membershipEventId, + membershipEventDigest, + lastTransitionInvalidated)); + if (!expectedAuthorityDigest.equals(authoritySnapshotDigest)) { + throw new IllegalArgumentException("Authority snapshot digest does not match its fields"); + } + String expectedDecisionDigest = + eligibilityDecisionDigestFor( + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + currentness, + decision, + expectedAuthorityDigest); + if (!expectedDecisionDigest.equals(eligibilityDecisionDigest)) { + throw new IllegalArgumentException("Eligibility decision digest does not match its fields"); + } + } + + /** Creates the two independently domain-separated digests for a verified owner snapshot. */ + public static AccountActorStagingEligibilityEvidence seal( + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + UUID canonicalTenantId, + Purpose purpose, + Instant observedAt, + String accountUuidProvenance, + String accountLifecycleState, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated) { + Decision decision = + "ACTIVE".equals(accountLifecycleState) + && "ACTIVE".equals(membershipLifecycleState) + && gameplayAdmissionAllowed + ? Decision.STAGING_ELIGIBLE + : Decision.STAGING_INELIGIBLE; + String authorityDigest = + authoritySnapshotDigestFor( + fields( + SCHEMA_VERSION, + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + Currentness.CURRENT_AT_REVALIDATION, + observedAt, + decision, + accountUuidProvenance, + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipAuthorityProvenance, + membershipVersion, + membershipAuthorityGeneration, + tenantProvenanceKind, + tenantSourceOperationId, + tenantProvenanceDigest, + membershipEventSequence, + membershipEventId, + membershipEventDigest, + lastTransitionInvalidated)); + String decisionDigest = + eligibilityDecisionDigestFor( + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + Currentness.CURRENT_AT_REVALIDATION, + decision, + authorityDigest); + return new AccountActorStagingEligibilityEvidence( + SCHEMA_VERSION, + targetNamespace, + requestId, + canonicalAccountId, + canonicalTenantId, + purpose, + Currentness.CURRENT_AT_REVALIDATION, + observedAt, + decision, + accountUuidProvenance, + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipAuthorityProvenance, + membershipVersion, + membershipAuthorityGeneration, + tenantProvenanceKind, + tenantSourceOperationId, + tenantProvenanceDigest, + membershipEventSequence, + membershipEventId, + membershipEventDigest, + lastTransitionInvalidated, + decisionDigest, + authorityDigest); + } + + public enum Purpose { + PUBLIC_PRODUCTION_STAGING_ONLY + } + + public enum Currentness { + CURRENT_AT_REVALIDATION + } + + public enum Decision { + STAGING_ELIGIBLE, + STAGING_INELIGIBLE + } + + private static List fields( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalAccountId, + UUID canonicalTenantId, + Purpose purpose, + Currentness currentness, + Instant observedAt, + Decision decision, + String accountUuidProvenance, + String accountLifecycleState, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipAuthorityProvenance, + long membershipVersion, + long membershipAuthorityGeneration, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipEventSequence, + UUID membershipEventId, + String membershipEventDigest, + boolean lastTransitionInvalidated) { + return List.of( + new Field("schemaVersion", Integer.toString(schemaVersion)), + new Field("targetNamespace", targetNamespace), + new Field("requestId", requestId.toString()), + new Field("canonicalAccountId", canonicalAccountId.toString()), + new Field("canonicalTenantId", canonicalTenantId.toString()), + new Field("purpose", purpose.name()), + new Field("currentness", currentness.name()), + new Field("observedAtEpochSecond", Long.toString(observedAt.getEpochSecond())), + new Field("observedAtNano", Integer.toString(observedAt.getNano())), + new Field("decision", decision.name()), + new Field("accountUuidProvenance", accountUuidProvenance), + new Field("accountLifecycleState", accountLifecycleState), + new Field("membershipLifecycleState", membershipLifecycleState), + new Field("gameplayAdmissionAllowed", Boolean.toString(gameplayAdmissionAllowed)), + new Field("membershipAuthorityProvenance", membershipAuthorityProvenance), + new Field("membershipVersion", Long.toString(membershipVersion)), + new Field("membershipAuthorityGeneration", Long.toString(membershipAuthorityGeneration)), + new Field("tenantProvenanceKind", tenantProvenanceKind), + new Field("tenantSourceOperationId", tenantSourceOperationId.toString()), + new Field("tenantProvenanceDigest", tenantProvenanceDigest), + new Field("membershipEventSequence", Long.toString(membershipEventSequence)), + new Field("membershipEventId", membershipEventId.toString()), + new Field("membershipEventDigest", membershipEventDigest), + new Field("lastTransitionInvalidated", Boolean.toString(lastTransitionInvalidated))); + } + + private static String authoritySnapshotDigestFor(List fields) { + return digest("firemud.account.actor-staging.authority-snapshot/v1", fields); + } + + private static String eligibilityDecisionDigestFor( + String namespace, + UUID requestId, + UUID accountId, + UUID tenantId, + Purpose purpose, + Currentness currentness, + Decision decision, + String authoritySnapshotDigest) { + return digest( + "firemud.account.actor-staging.eligibility-decision/v1", + List.of( + new Field("targetNamespace", namespace), + new Field("requestId", requestId.toString()), + new Field("canonicalAccountId", accountId.toString()), + new Field("canonicalTenantId", tenantId.toString()), + new Field("purpose", purpose.name()), + new Field("currentness", currentness.name()), + new Field("decision", decision.name()), + new Field("authoritySnapshotDigest", authoritySnapshotDigest))); + } + + private static String digest(String domain, List fields) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writeUtf8(output, domain); + output.writeInt(fields.size()); + for (Field field : fields) { + writeUtf8(output, field.name()); + writeUtf8(output, field.value()); + } + } + return hex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode Account actor-staging evidence", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void writeUtf8(DataOutputStream output, String value) throws IOException { + ByteBuffer encoded; + try { + encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Evidence contains malformed UTF-16", exception); + } + byte[] valueBytes = new byte[encoded.remaining()]; + encoded.get(valueBytes); + output.writeInt(valueBytes.length); + output.write(valueBytes); + } + + private static void requireStrictUtf8(String value, String label) { + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(label + " is not valid UTF-8", exception); + } + } + + private static String hex(byte[] digest) { + StringBuilder value = new StringBuilder(digest.length * 2); + for (byte octet : digest) { + value.append(Character.forDigit((octet >>> 4) & 0x0f, 16)); + value.append(Character.forDigit(octet & 0x0f, 16)); + } + return value.toString(); + } + + private static void requireDigest(String value, Pattern pattern, String label) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical lowercase SHA-256 hex"); + } + } + + private static void requireMember(String value, List allowed, String label) { + if (value == null || !allowed.contains(value)) { + throw new IllegalArgumentException(label + " is not recognized"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a nonnil UUID"); + } + } + + private record Field(String name, String value) { + private Field { + Objects.requireNonNull(name); + Objects.requireNonNull(value); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java new file mode 100644 index 0000000000..ece7e54a82 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java @@ -0,0 +1,662 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable source material, not an authorization decision or authenticated actor proof. */ +public record DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources, + String schemaVersion, + List requiredOwners) { + + public static final String SCHEMA = "account-draft-authorization-fence/v1"; + public static final String SCHEMA_V1 = SCHEMA; + public static final String SCHEMA_V2 = "account-draft-authorization-fence/v2"; + private static final List V1_OWNERS = List.of(Owner.GAME_DESIGN, Owner.WORLD); + + /** Retains the original producer's exact v1 frame and fixed owner vector. */ + public DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources) { + this( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V1, + V1_OWNERS); + } + + public DraftAuthorizationFenceBinding { + Objects.requireNonNull(schemaVersion, "schemaVersion"); + requiredOwners = List.copyOf(Objects.requireNonNull(requiredOwners, "requiredOwners")); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + requireUuid(id); + } + text(baseCommitId); + if (baseCommitId.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException("Base commit exceeds 256 UTF-8 bytes"); + } + decimal(expectedDraftEpoch, true); + gameDesignBinding = bytes(gameDesignBinding); + normalizedInput = bytes(normalizedInput); + DraftCommitBinding completeBinding; + try { + completeBinding = + DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException( + "Complete canonical Game Design binding required", corrupt); + } + if (!Arrays.equals(gameDesignBinding, completeBinding.canonicalBytes()) + || !requestId.equals(completeBinding.requestId()) + || !commitId.equals(completeBinding.commitId()) + || !tenantId.equals(completeBinding.target().canonicalTenantId()) + || !versionId.equals(completeBinding.target().canonicalVersionId()) + || !baseCommitId.equals(completeBinding.baseCommitId())) { + throw new IllegalArgumentException("Account fence differs from complete Game Design binding"); + } + if (!Arrays.equals(normalizedInput, gameDesignBinding) + || !completeBinding.digest().equals(inputDigest)) { + throw new IllegalArgumentException( + "Draft input must be the exact complete canonical binding"); + } + sources = List.copyOf(Objects.requireNonNull(sources)); + if (sources.isEmpty()) { + throw new IllegalArgumentException("Applicable Account sources are required"); + } + sources = sources.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Duplicate Account source scope"); + } + if (SCHEMA_V1.equals(schemaVersion)) { + if (!V1_OWNERS.equals(requiredOwners)) { + throw new IllegalArgumentException("V1 Draft authorization owners are fixed"); + } + } else if (SCHEMA_V2.equals(schemaVersion)) { + List canonicalOwners = requiredOwners(completeBinding); + if (!canonicalOwners.equals(requiredOwners)) { + throw new IllegalArgumentException( + "V2 Draft authorization owners must exactly match the complete binding"); + } + } else { + throw new IllegalArgumentException("Unsupported Draft authorization fence schema"); + } + } + + /** Converts this exact authorization input to v2 with its canonical complete owner set. */ + public DraftAuthorizationFenceBinding withRequiredOwners() { + DraftCommitBinding completeBinding = completeGameDesignBinding(); + return new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V2, + requiredOwners(completeBinding)); + } + + private DraftCommitBinding completeGameDesignBinding() { + return DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } + + private static List requiredOwners(DraftCommitBinding binding) { + EnumSet owners = EnumSet.of(Owner.GAME_DESIGN); + for (DraftCommitBinding.Owner owner : binding.requiredOwners()) { + owners.add( + switch (owner) { + case WORLD_MANAGEMENT -> Owner.WORLD; + case ENTITY_MANAGEMENT -> Owner.ENTITY; + case GAME_LOGIC -> Owner.GAME_LOGIC; + case AUTOMATION_SCRIPTING -> Owner.AUTOMATION; + case GAME_DESIGN_CONTROL_PLANE -> Owner.GAME_DESIGN; + }); + } + return Arrays.stream(Owner.values()).filter(owners::contains).toList(); + } + + /** + * Reconstructs only exact supported immutable Draft-fence framing; this grants no authorization. + */ + public static DraftAuthorizationFenceBinding fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + String schemaVersion = reader.text(); + if (!SCHEMA_V1.equals(schemaVersion) && !SCHEMA_V2.equals(schemaVersion)) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + UUID operationId = canonicalUuidValue(reader.text()); + UUID requestId = canonicalUuidValue(reader.text()); + UUID commitId = canonicalUuidValue(reader.text()); + UUID fenceId = canonicalUuidValue(reader.text()); + UUID actorAccountId = canonicalUuidValue(reader.text()); + UUID tenantId = canonicalUuidValue(reader.text()); + UUID versionId = canonicalUuidValue(reader.text()); + String baseCommitId = reader.text(); + reader.expect("DRAFT"); + String expectedDraftEpoch = reader.text(); + byte[] gameDesignBinding = reader.bytes(); + byte[] normalizedInput = reader.bytes(); + String inputDigest = reader.text(); + String countText = reader.text(); + decimal(countText, false); + BigInteger sourceCount = new BigInteger(countText); + if (sourceCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + int sourceCountValue = sourceCount.intValueExact(); + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int index = 0; index < sourceCountValue; index++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + List requiredOwners; + if (SCHEMA_V1.equals(schemaVersion)) { + reader.expect("GAME_DESIGN"); + reader.expect("WORLD"); + requiredOwners = V1_OWNERS; + } else { + String ownerCountText = reader.text(); + decimal(ownerCountText, false); + BigInteger ownerCount = new BigInteger(ownerCountText); + if (ownerCount.compareTo(BigInteger.valueOf(Owner.values().length)) > 0 + || ownerCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Invalid stored required-owner vector"); + } + int ownerCountValue = ownerCount.intValueExact(); + java.util.ArrayList storedOwners = new java.util.ArrayList<>(); + for (int index = 0; index < ownerCountValue; index++) { + storedOwners.add(Owner.valueOf(reader.text())); + } + requiredOwners = List.copyOf(storedOwners); + } + reader.requireEnd(); + + DraftAuthorizationFenceBinding binding = + new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + schemaVersion, + requiredOwners); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored authorization fence binding"); + } + return binding; + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + @Override + public byte[] gameDesignBinding() { + return gameDesignBinding.clone(); + } + + @Override + public byte[] normalizedInput() { + return normalizedInput.clone(); + } + + /** Closed, ordered UTF-8/binary length frames; counters are exact decimal strings. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, schemaVersion); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + frame(output, id.toString()); + } + frame(output, baseCommitId); + frame(output, "DRAFT"); + frame(output, expectedDraftEpoch); + frame(output, gameDesignBinding); + frame(output, normalizedInput); + frame(output, inputDigest); + frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frame(output, source.canonicalBytes()); + } + if (SCHEMA_V1.equals(schemaVersion)) { + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + } else { + frame(output, Integer.toString(requiredOwners.size())); + for (Owner owner : requiredOwners) { + frame(output, owner.name()); + } + } + return output.toByteArray(); + } + + public enum SourceKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP, + GLOBAL_ROLES, + CREATOR_PARTY, + HOSTED_TERMS + } + + /** + * Independent owner counters/checkpoints and exact existing source evidence; no inferred epochs. + */ + public record SourceEvidence( + SourceKind kind, + String scopeId, + String generation, + String sourceVersion, + String checkpointStream, + String checkpointSequence, + byte[] evidence) { + public SourceEvidence { + Objects.requireNonNull(kind); + text(scopeId); + // Preserve the exact configured issuer, including its supported 512-character Unicode + // identity. Bound the complete index key in bytes rather than truncating or aliasing it. + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 2048) { + throw new IllegalArgumentException("Source participation key exceeds 2048 UTF-8 bytes"); + } + if (kind == SourceKind.ACCOUNT + || kind == SourceKind.TENANT + || kind == SourceKind.GLOBAL_ROLES) { + canonicalUuid(scopeId); + } + if (kind == SourceKind.MEMBERSHIP) { + String[] pair = scopeId.split("/", -1); + if (pair.length != 2) { + throw new IllegalArgumentException("Canonical membership pair required"); + } + canonicalUuid(pair[0]); + canonicalUuid(pair[1]); + } + if (generation != null) { + decimal(generation, false); + } + decimal(sourceVersion, false); + if ((checkpointStream == null) != (checkpointSequence == null)) { + throw new IllegalArgumentException("Checkpoint fields must be applicable together"); + } + if (checkpointStream != null) { + text(checkpointStream); + decimal(checkpointSequence, true); + } + evidence = bytes(evidence); + } + + @Override + public byte[] evidence() { + return evidence.clone(); + } + + public String key() { + return kind.name() + ":" + scopeId; + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : List.of("account-draft-source-evidence/v1", kind.name(), scopeId)) { + frame(output, value); + } + frame(output, generation == null ? "ABSENT" : "PRESENT"); + if (generation != null) { + frame(output, generation); + } + frame(output, sourceVersion); + frame(output, checkpointStream == null ? "ABSENT" : "PRESENT"); + if (checkpointStream != null) { + frame(output, checkpointStream); + frame(output, checkpointSequence); + } + frame(output, evidence); + return output.toByteArray(); + } + + /** Decodes only the exact immutable framing written by this source owner. */ + public static SourceEvidence fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect("account-draft-source-evidence/v1"); + SourceKind kind = SourceKind.valueOf(reader.text()); + String scope = reader.text(); + String generation = reader.optionalText(); + String version = reader.text(); + String stream = reader.optionalText(); + String sequence = stream == null ? null : reader.text(); + SourceEvidence source = + new SourceEvidence(kind, scope, generation, version, stream, sequence, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, source.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source evidence"); + } + return source; + } + } + + /** Bounded exact frame decoding for persisted source evidence and source-change intent. */ + public static final class FrameReader { + private final ByteBuffer input; + + public FrameReader(byte[] stored) { + input = ByteBuffer.wrap(DraftAuthorizationFenceBinding.bytes(stored)); + } + + public byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated immutable source frame"); + } + int size = input.getInt(); + if (size < 0 || size > input.remaining()) { + throw new IllegalArgumentException("Invalid immutable source frame size"); + } + byte[] value = new byte[size]; + input.get(value); + return value; + } + + public String text() { + byte[] value = bytes(); + String text = new String(value, StandardCharsets.UTF_8); + DraftAuthorizationFenceBinding.text(text); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 source frame"); + } + return text; + } + + public String optionalText() { + String presence = text(); + if ("ABSENT".equals(presence)) { + return null; + } + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid immutable source presence"); + } + return text(); + } + + public void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + } + + public int remaining() { + return input.remaining(); + } + + public void requireEnd() { + if (input.hasRemaining()) { + throw new IllegalArgumentException("Trailing immutable source frames"); + } + } + } + + public enum Owner { + GAME_DESIGN, + WORLD, + ENTITY, + GAME_LOGIC, + AUTOMATION + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + private static final String OWNER_READBACK_SCHEMA_V1 = "account-draft-owner-readback/v1"; + private static final String OWNER_READBACK_SCHEMA_V2 = "account-draft-owner-readback/v2"; + + /** Only a future authenticated owner verifier may supply this exact durable readback. */ + public record OwnerReadback( + Owner owner, + Outcome outcome, + UUID operationId, + UUID commitId, + UUID fenceId, + String inputDigest, + byte[] fullBinding, + byte[] result) { + public OwnerReadback { + Objects.requireNonNull(owner); + Objects.requireNonNull(outcome); + requireUuid(operationId); + requireUuid(commitId); + requireUuid(fenceId); + if (inputDigest == null || !inputDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical digest required"); + } + fullBinding = bytes(fullBinding); + result = bytes(result); + } + + /** Reads only canonical original evidence; decoding does not authenticate its producer. */ + public static OwnerReadback fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + String schema = reader.text(); + if (!OWNER_READBACK_SCHEMA_V1.equals(schema) && !OWNER_READBACK_SCHEMA_V2.equals(schema)) { + throw new IllegalArgumentException("Unsupported stored owner readback schema"); + } + OwnerReadback readback = + new OwnerReadback( + Owner.valueOf(reader.text()), + Outcome.valueOf(reader.text()), + canonicalUuidValue(reader.text()), + canonicalUuidValue(reader.text()), + canonicalUuidValue(reader.text()), + reader.text(), + reader.bytes(), + reader.bytes()); + reader.requireEnd(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(readback.fullBinding()); + if (!schema.equals(readbackSchema(binding))) { + throw new IllegalArgumentException("Owner readback schema differs from its full binding"); + } + readback.requireBinding(binding); + if (!Arrays.equals(stored, readback.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored owner readback"); + } + return readback; + } + + @Override + public byte[] fullBinding() { + return fullBinding.clone(); + } + + @Override + public byte[] result() { + return result.clone(); + } + + public void requireBinding(DraftAuthorizationFenceBinding binding) { + if (!operationId.equals(binding.operationId()) + || !commitId.equals(binding.commitId()) + || !fenceId.equals(binding.fenceId()) + || !inputDigest.equals(binding.inputDigest()) + || !Arrays.equals(fullBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Owner readback differs from complete Draft binding"); + } + if (SCHEMA_V2.equals(binding.schemaVersion()) && !binding.requiredOwners().contains(owner)) { + throw new IllegalArgumentException("Owner readback owner is not required by Draft binding"); + } + if (SCHEMA_V1.equals(binding.schemaVersion()) && !V1_OWNERS.contains(owner)) { + throw new IllegalArgumentException("V1 owner readback owner is outside its closed schema"); + } + } + + public byte[] canonicalBytes() { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(fullBinding); + requireBinding(binding); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + readbackSchema(binding), + owner.name(), + outcome.name(), + operationId.toString(), + commitId.toString(), + fenceId.toString(), + inputDigest)) { + frame(output, value); + } + frame(output, fullBinding); + frame(output, result); + return output.toByteArray(); + } + + private static String readbackSchema(DraftAuthorizationFenceBinding binding) { + return SCHEMA_V1.equals(binding.schemaVersion()) + ? OWNER_READBACK_SCHEMA_V1 + : OWNER_READBACK_SCHEMA_V2; + } + } + + public static byte[] bytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact bytes required"); + } + return value.clone(); + } + + public static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + public static void canonicalUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + } + + static void text(String value) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("Nonempty canonical text required"); + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } else if (Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } + } + + public static void decimal(String value, boolean zero) { + if (value == null || !value.matches(zero ? "0|[1-9][0-9]*" : "[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical decimal string required"); + } + } + + public static void frame(ByteArrayOutputStream output, String value) { + text(value); + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + public static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID canonicalUuidValue(String value) { + canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java new file mode 100644 index 0000000000..8125e71961 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftBaseReference.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Objects; +import java.util.UUID; + +/** Closed v1 reviewed-base grammar; a genesis receipt is never an authored commit. */ +public record DraftBaseReference(Kind kind, UUID identity) { + public static final String SCHEMA = "game-design-draft-base-reference/v1"; + + public enum Kind { + GENESIS, + AUTHORED_COMMIT + } + + public DraftBaseReference { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(identity, "identity"); + if (identity.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Reviewed base identity must be nonnil"); + } + } + + public static DraftBaseReference parse(String value) { + Objects.requireNonNull(value, "value"); + Kind kind = value.startsWith("genesis:") ? Kind.GENESIS : Kind.AUTHORED_COMMIT; + String token = kind == Kind.GENESIS ? value.substring(8) : value; + if (!token.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw new IllegalArgumentException("Canonical v1 reviewed base required"); + } + return new DraftBaseReference(kind, UUID.fromString(token)); + } + + public String canonicalValue() { + return (kind == Kind.GENESIS ? "genesis:" : "") + identity; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java new file mode 100644 index 0000000000..99241c05f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java @@ -0,0 +1,454 @@ +package net.firedevops.firemud.common.authoring; + +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.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete immutable Game Design binding for one coordinated Draft commit. + * + *

This type retains a declared mutation and its affected tuple set exactly. Its owner labels and + * opaque payloads are not proof that the declaration is semantically complete; each typed owner + * producer must derive and verify its required tuple subset before any owner action. + */ +public final class DraftCommitBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator AFFECTED_ORDER = + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId); + + /** Owners participating in the canonical multi-owner Draft commit contract. */ + public enum Owner { + WORLD_MANAGEMENT, + ENTITY_MANAGEMENT, + GAME_LOGIC, + AUTOMATION_SCRIPTING, + GAME_DESIGN_CONTROL_PLANE + } + + /** Canonical identity plus the exact private Game Design Version/source lineage. */ + public record TargetProof( + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId, + String gameDesignVersionTenantKey, + long sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind) { + public TargetProof { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (gameDesignVersionRowId <= 0 || sourceGameRowId <= 0) { + throw new IllegalArgumentException("Game Design source row identities must be positive"); + } + requireBoundedText(gameDesignVersionTenantKey, 36, "gameDesignVersionTenantKey"); + requireBoundedText(sourceGameTenantKey, 36, "sourceGameTenantKey"); + if (!gameDesignVersionTenantKey.equals(sourceGameTenantKey)) { + throw new IllegalArgumentException( + "Version and source Game Design tenant keys must match exactly"); + } + if (!"NEW_GAME_ROW".equals(sourceProvenanceKind) + && !"RETAINED_GAME_V29".equals(sourceProvenanceKind)) { + throw new IllegalArgumentException("Unsupported canonical Version source provenance"); + } + } + } + + /** One full owner-typed revision payload. The payload is opaque and is never normalized here. */ + public record RevisionPayload( + String revisionOrder, UUID revisionId, Owner owner, String payload) { + public RevisionPayload { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(payload, "payload"); + } + } + + /** The expected epoch for one owner-local aggregate and scope fence. */ + public record AffectedUnit( + Owner owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public AffectedUnit { + Objects.requireNonNull(owner, "owner"); + requireBoundedText(aggregateType, 128, "aggregateType"); + requireBoundedText(aggregateId, 256, "aggregateId"); + requireBoundedText(scopeType, 128, "scopeType"); + requireBoundedText(scopeId, 256, "scopeId"); + requireCanonicalCounter(expectedEpoch, "expectedEpoch"); + } + } + + private final TargetProof target; + private final UUID requestId; + private final UUID commitId; + private final String baseCommitId; + private final List revisions; + private final List affectedUnits; + private final List requiredOwners; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private DraftCommitBinding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + this.target = Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + requireBoundedText(baseCommitId, 256, "baseCommitId"); + this.requestId = requestId; + this.commitId = commitId; + this.baseCommitId = baseCommitId; + this.revisions = validateRevisions(revisions); + this.affectedUnits = validateAffectedUnits(affectedUnits); + this.requiredOwners = validateOwnerCoverage(this.revisions, this.affectedUnits); + try { + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialize(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft commit binding could not be canonicalized", exception); + } + } + + public static DraftCommitBinding create( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + return new DraftCommitBinding( + target, requestId, commitId, baseCommitId, revisions, affectedUnits); + } + + /** Reconstructs an immutable binding from owner storage and rejects noncanonical/corrupt rows. */ + public static DraftCommitBinding fromStored(String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + JsonNode targetNode = requireObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(root, "canonicalTenantId")), + UUID.fromString(requiredText(root, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + List revisions = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "revisions")) { + revisions.add( + new RevisionPayload( + requiredText(node, "revisionOrder"), + UUID.fromString(requiredText(node, "revisionId")), + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "payload"))); + } + List affectedUnits = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "affectedUnits")) { + affectedUnits.add( + new AffectedUnit( + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"))); + } + DraftCommitBinding binding = + create( + target, + UUID.fromString(requiredText(root, "requestId")), + UUID.fromString(requiredText(root, "commitId")), + requiredText(root, "baseCommitId"), + revisions, + affectedUnits); + if (!binding.canonicalJson.equals(storedJson) + || !binding.digest.equals(storedDigest) + || !Arrays.equals(binding.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored Draft commit binding is not exact canonical JSON"); + } + return binding; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored Draft commit binding is corrupt", exception); + } + } + + public TargetProof target() { + return target; + } + + public UUID requestId() { + return requestId; + } + + public UUID commitId() { + return commitId; + } + + public String baseCommitId() { + return baseCommitId; + } + + public List revisions() { + return List.copyOf(revisions); + } + + public List affectedUnits() { + return List.copyOf(affectedUnits); + } + + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + /** The canonical UTF-8 representation, retained as text for exact database equality. */ + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a defensive copy of the exact RFC 8785 bytes stored with this binding. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public List affectedUnits(Owner owner) { + return affectedUnits.stream().filter(unit -> unit.owner() == owner).toList(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftCommitBinding binding + && digest.equals(binding.digest) + && Arrays.equals(canonicalBytes, binding.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map object = new LinkedHashMap<>(); + object.put("schemaVersion", "1"); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + Map targetObject = new LinkedHashMap<>(); + targetObject.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + targetObject.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + targetObject.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + targetObject.put("sourceGameTenantKey", target.sourceGameTenantKey()); + targetObject.put("sourceProvenanceKind", target.sourceProvenanceKind()); + object.put("target", targetObject); + object.put("requestId", requestId.toString()); + object.put("commitId", commitId.toString()); + object.put("baseCommitId", baseCommitId); + object.put("revisions", revisions.stream().map(DraftCommitBinding::revisionJson).toList()); + object.put( + "affectedUnits", affectedUnits.stream().map(DraftCommitBinding::affectedUnitJson).toList()); + object.put("requiredOwners", requiredOwners.stream().map(Enum::name).toList()); + return object; + } + + private static Map revisionJson(RevisionPayload revision) { + Map object = new LinkedHashMap<>(); + object.put("revisionOrder", revision.revisionOrder()); + object.put("revisionId", revision.revisionId().toString()); + object.put("owner", revision.owner().name()); + object.put("payload", revision.payload()); + return object; + } + + private static Map affectedUnitJson(AffectedUnit unit) { + Map object = new LinkedHashMap<>(); + object.put("owner", unit.owner().name()); + object.put("aggregateType", unit.aggregateType()); + object.put("aggregateId", unit.aggregateId()); + object.put("scopeType", unit.scopeType()); + object.put("scopeId", unit.scopeId()); + object.put("expectedEpoch", unit.expectedEpoch()); + return object; + } + + private static List validateRevisions(List requested) { + Objects.requireNonNull(requested, "revisions"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must contain at least one full revision"); + } + List copy = List.copyOf(requested); + Set revisionIds = new HashSet<>(); + for (int index = 0; index < copy.size(); index++) { + RevisionPayload revision = Objects.requireNonNull(copy.get(index), "revision"); + if (!Integer.toString(index).equals(revision.revisionOrder())) { + throw new IllegalArgumentException( + "Revision order must be the contiguous canonical array order"); + } + if (!revisionIds.add(revision.revisionId())) { + throw new IllegalArgumentException("Draft commit contains a duplicate revision identity"); + } + if (revision.payload().isEmpty()) { + throw new IllegalArgumentException("A full revision payload must not be omitted"); + } + } + return copy; + } + + private static List validateAffectedUnits(List requested) { + Objects.requireNonNull(requested, "affectedUnits"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must declare its complete affected units"); + } + List copy = new ArrayList<>(requested.size()); + Set identities = new HashSet<>(); + for (AffectedUnit unit : requested) { + Objects.requireNonNull(unit, "affectedUnit"); + String identity = + unit.owner() + + "\u0000" + + unit.aggregateType() + + "\u0000" + + unit.aggregateId() + + "\u0000" + + unit.scopeType() + + "\u0000" + + unit.scopeId(); + if (!identities.add(identity)) { + throw new IllegalArgumentException( + "Draft commit contains a duplicate affected owner scope"); + } + copy.add(unit); + } + copy.sort(AFFECTED_ORDER); + return List.copyOf(copy); + } + + private static List validateOwnerCoverage( + List revisions, List affectedUnits) { + Set revisionOwners = new HashSet<>(); + revisions.forEach(revision -> revisionOwners.add(revision.owner())); + Set affectedOwners = new HashSet<>(); + affectedUnits.forEach(unit -> affectedOwners.add(unit.owner())); + if (!revisionOwners.equals(affectedOwners)) { + throw new IllegalArgumentException( + "Required owner set must exactly match owners derived from revisions and affected units"); + } + return Arrays.stream(Owner.values()).filter(revisionOwners::contains).toList(); + } + + private static String serialize(Object object) { + return JSON.writeValueAsString(object); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing text field " + field); + } + return value.textValue(); + } + + private static JsonNode requireObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing object field " + field); + } + return value; + } + + private static JsonNode requiredArray(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing array field " + field); + } + return value; + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireCanonicalCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + new BigInteger(value); + } + + private static void requireBoundedText(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes + || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank canonical bounded text"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java new file mode 100644 index 0000000000..21aac2639d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** + * Validated World terminal-read value; peer authentication is supplied only by transport guards. + */ +public record WorldDraftTerminalReadEvidence( + Request request, Optional ownerReadback) { + public WorldDraftTerminalReadEvidence { + Objects.requireNonNull(request, "request"); + ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); + ownerReadback.ifPresent( + value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.WORLD + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED + && value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED)) { + throw new IllegalArgumentException("World readback must be an exact terminal outcome"); + } + DraftAuthorizationFenceBinding binding = request.accountBinding(); + value.requireBinding(binding); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World readback differs from the original binding"); + } + if (value.outcome() == DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, value); + } + }); + } + + /** The canonical original Account binding and a separate caller-owned fresh read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World terminal read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + if (originalAccountBinding == null || originalAccountBinding.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + originalAccountBinding = originalAccountBinding.clone(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException("World terminal read requires a fresh request identity"); + } + } + + public static Request create(String targetNamespace, byte[] originalAccountBinding) { + return new Request( + SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalAccountBinding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding accountBinding() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + return 31 * result + Arrays.hashCode(originalAccountBinding); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + label + " is required"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..a826e79d17 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -0,0 +1,736 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed request mapping and exact echo/outcome validation for authenticated World readback. */ +public final class WorldDraftTerminalReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String APPLIED_V1 = "world-draft-graph-applied/v1"; + private static final String APPLIED_V2 = "world-draft-graph-applied/v2"; + private static final java.util.List FRESH_GRAPH_FAMILIES = + java.util.List.of( + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", + "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING"); + private static final Set APPLIED_V1_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "appliedEpochs"); + private static final Set APPLIED_V2_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "startLocationReceiptBase64", + "startLocationReceiptDigest", + "appliedEpochs"); + private static final Set FRESH_GRAPH_DECLARATION_FIELDS = + Set.of("tenantId", "versionId", "startLocation", "familyCounts"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set FAMILY_COUNT_FIELDS = Set.of("family", "count"); + private static final Set GRAPH_ROW_FIELDS = Set.of("mapping", "content"); + private static final Set GRAPH_MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + private static final Set WORLD_MUTATION_FIELDS = + Set.of( + "logicalRevisionId", + "commitId", + "operation", + "aggregateType", + "aggregateId", + "expectedDraftRevisionEpoch", + "scopeType", + "scopeId", + "expectedDraftScopeRevisionEpoch", + "scopeMutationPolicy", + "freshGraphDeclaration", + "region", + "zone", + "room", + "roomExit", + "generationRule", + "worldEntitySpawnBinding", + "worldGenerationSubtree"); + private static final tools.jackson.databind.ObjectMapper JSON = + JsonMapper.builder() + .enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private WorldDraftTerminalReadGrpcCodec() {} + + public static ReadWorldDraftTerminalOutcomeRequest toRequest( + WorldDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldDraftTerminalOutcomeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** Decodes only after the receiver has authenticated its exact same-namespace Account peer. */ + public static WorldDraftTerminalReadEvidence.Request fromRequest( + ReadWorldDraftTerminalOutcomeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldDraftTerminalOutcomeRequest"); + try { + return new WorldDraftTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getOriginalAccountBinding().toByteArray()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("World terminal read request is invalid", exception); + } + } + + /** Emits only UNKNOWN or exact canonical World committed/definitive-abort readback. */ + public static ReadWorldDraftTerminalOutcomeResponse toResponse( + WorldDraftTerminalReadEvidence.Request request, + Optional ownerReadback) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(ownerReadback, "ownerReadback"); + var builder = + ReadWorldDraftTerminalOutcomeResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())); + if (ownerReadback.isEmpty()) { + return builder + .setStatus(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN) + .build(); + } + var readback = ownerReadback.orElseThrow(); + requireExactOwnerReadback(request, readback); + return builder + .setStatus( + readback.outcome() == Outcome.COMMITTED + ? WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + : WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(readback.canonicalBytes())) + .build(); + } + + /** Validates the complete echo and independently framed World owner result. */ + public static WorldDraftTerminalReadEvidence fromResponse( + WorldDraftTerminalReadEvidence.Request request, + ReadWorldDraftTerminalOutcomeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldDraftTerminalOutcomeResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World terminal response changed the exact read request"); + } + Optional readback; + switch (response.getStatus()) { + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN -> { + if (!response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("UNKNOWN World readback cannot carry a result"); + } + readback = Optional.empty(); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED, + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED -> { + if (response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("World terminal readback bytes are required"); + } + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + response.getOwnerReadbackBytes().toByteArray()); + requireExactOwnerReadback(request, decoded); + Outcome expected = + response.getStatus() + == WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + ? Outcome.COMMITTED + : Outcome.DEFINITIVELY_ABORTED; + if (decoded.outcome() != expected) { + throw new IllegalArgumentException( + "World terminal status differs from canonical owner outcome"); + } + readback = Optional.of(decoded); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unsupported World terminal read status"); + default -> throw new IllegalArgumentException("Unsupported World terminal read status"); + } + return new WorldDraftTerminalReadEvidence(request, readback); + } + + private static void requireExactOwnerReadback( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + DraftAuthorizationFenceBinding binding = request.accountBinding(); + if (readback.owner() != Owner.WORLD + || (readback.outcome() != Outcome.DEFINITIVELY_ABORTED + && readback.outcome() != Outcome.COMMITTED)) { + throw new IllegalArgumentException( + "World terminal response is not an exact World terminal outcome"); + } + readback.requireBinding(binding); + if (!readback.operationId().equals(binding.operationId()) + || !readback.commitId().equals(binding.commitId()) + || !readback.fenceId().equals(binding.fenceId()) + || !readback.inputDigest().equals(binding.inputDigest()) + || !Arrays.equals(readback.fullBinding(), request.originalAccountBinding()) + || readback.result().length == 0) { + throw new IllegalArgumentException( + "World terminal response differs from the complete original Account binding"); + } + if (readback.outcome() == Outcome.COMMITTED) requireCommittedResult(request, readback); + } + + /** + * Checks this World carrier only; mutation/source semantics remain at the authenticated owner. + */ + static void requireCommittedResult( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + try { + byte[] bytes = readback.result(); + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) + throw new IllegalArgumentException("Noncanonical World APPLIED result"); + JsonNode result = JSON.readTree(bytes); + String schema = text(result, "schema"); + boolean v2 = APPLIED_V2.equals(schema); + if (!v2 && !APPLIED_V1.equals(schema)) { + throw new IllegalArgumentException("Unsupported World APPLIED result schema"); + } + fields(result, v2 ? APPLIED_V2_FIELDS : APPLIED_V1_FIELDS); + exactText(result, "status", "APPLIED"); + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(account.tenantId()) + || !draft.target().canonicalVersionId().equals(account.versionId())) { + throw new IllegalArgumentException("World applied input differs from original binding"); + } + OriginalFreshGraph originalGraph = readOriginalFreshGraph(draft, v2); + if (v2 != (originalGraph != null)) { + throw new IllegalArgumentException( + "World APPLIED schema does not match the original fresh graph declaration"); + } + FrameReader operation = new FrameReader(base64(result, "operationBytesBase64")); + operation.expect("world-draft-terminal-operation/v1"); + for (UUID id : + java.util.List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) operation.expect(id.toString()); + operation.expectBytes(draft.canonicalBytes()); + operation.expect(request.targetNamespace()); + operation.expect(account.tenantId().toString()); + operation.expect(account.versionId().toString()); + UUID versionIdentityOperationId = operation.canonicalUuid(); + operation.expect(Long.toString(draft.target().gameDesignVersionRowId())); + operation.canonicalUuid(); // Intake request + operation.canonicalUuid(); // Intake operation + operation.digest(); // Intake request digest + operation.canonicalUuid(); // Source operation + operation.digest(); // Source evidence digest + operation.digest(); // Intake receipt digest + operation.expect(sha256(request.originalAccountBinding())); + operation.expectBytes(request.originalAccountBinding()); + operation.requireEnd(); + byte[] graph = base64(result, "graphBytesBase64"); + if (v2) { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(graph)); + } + String graphDigest = sha256(graph); + exactText(result, "graphDigest", graphDigest); + JsonNode graphValue = JSON.readTree(graph); + fields( + graphValue, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + exactText(graphValue, "schemaVersion", "2"); + exactText(graphValue, "canonicalTenantId", account.tenantId().toString()); + exactText(graphValue, "canonicalVersionId", account.versionId().toString()); + if (!graphValue.get("rows").isArray() || graphValue.get("rows").isEmpty()) + throw new IllegalArgumentException("World applied graph is absent"); + if (v2) { + validateDeclaredGraphRows( + graphValue.get("rows"), + originalGraph, + request.targetNamespace(), + account, + versionIdentityOperationId); + validateStartLocationReceipt(result, graphDigest, originalGraph, request, draft, account); + } + var expected = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + JsonNode epochs = result.get("appliedEpochs"); + if (!epochs.isArray() || expected.isEmpty() || epochs.size() != expected.size()) + throw new IllegalArgumentException("World applied epoch vector is incomplete"); + for (int i = 0; i < expected.size(); i++) { + var unit = expected.get(i); + JsonNode epoch = epochs.get(i); + fields( + epoch, + Set.of( + "aggregateType", + "aggregateId", + "scopeType", + "scopeId", + "expectedEpoch", + "resultingEpoch")); + exactText(epoch, "aggregateType", unit.aggregateType()); + exactText(epoch, "aggregateId", unit.aggregateId()); + exactText(epoch, "scopeType", unit.scopeType()); + exactText(epoch, "scopeId", unit.scopeId()); + exactText(epoch, "expectedEpoch", unit.expectedEpoch()); + exactText( + epoch, + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()); + } + } catch (java.io.IOException | NoSuchAlgorithmException | RuntimeException invalid) { + throw new IllegalArgumentException( + "World committed readback has an invalid or substituted canonical APPLIED result", + invalid); + } + } + + private static OriginalFreshGraph readOriginalFreshGraph( + DraftCommitBinding draft, boolean requireCompleteDeclaration) throws java.io.IOException { + Map nodes = new LinkedHashMap<>(); + JsonNode declaration = null; + for (DraftCommitBinding.RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation; + try { + mutation = JSON.readTree(revision.payload()); + } catch (RuntimeException invalidPayload) { + if (requireCompleteDeclaration) throw invalidPayload; + // Retained v1 payloads predate a common JSON shape; they cannot declare a new typed + // selector. + continue; + } + if (mutation == null || !mutation.isObject()) { + if (requireCompleteDeclaration) { + throw new IllegalArgumentException("Original World mutation payload is not an object"); + } + continue; + } + JsonNode graphDeclaration = mutation.get("freshGraphDeclaration"); + if (!requireCompleteDeclaration) { + if (graphDeclaration != null) { + throw new IllegalArgumentException( + "Historical World APPLIED v1 cannot downgrade a declared fresh graph"); + } + continue; + } + fieldsKnown(mutation, WORLD_MUTATION_FIELDS); + exactText(mutation, "logicalRevisionId", revision.revisionId().toString()); + exactText(mutation, "commitId", draft.commitId().toString()); + String family = text(mutation, "aggregateType"); + if (!FRESH_GRAPH_FAMILIES.contains(family)) { + throw new IllegalArgumentException("Unsupported family in declared World graph input"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mutation, "aggregateId"), "aggregateId"); + String key = family + ":" + templateId; + if (nodes.putIfAbsent( + key, + new OriginalGraphNode( + family, templateId, revision.revisionId(), revision.revisionOrder())) + != null) { + throw new IllegalArgumentException("Original declared World graph repeats a template"); + } + if (graphDeclaration != null) { + if (declaration != null) { + throw new IllegalArgumentException( + "Original World input has multiple graph declarations"); + } + declaration = graphDeclaration; + } + } + if (!requireCompleteDeclaration) return null; + if (declaration == null || nodes.isEmpty()) { + throw new IllegalArgumentException( + "World v2 requires an original complete graph declaration"); + } + return parseOriginalFreshGraph(declaration, nodes, draft); + } + + private static OriginalFreshGraph parseOriginalFreshGraph( + JsonNode declaration, Map nodes, DraftCommitBinding draft) { + fields(declaration, FRESH_GRAPH_DECLARATION_FIELDS); + UUID tenantId = parseCanonicalNonNilUuid(text(declaration, "tenantId"), "declaration tenantId"); + UUID versionId = + parseCanonicalNonNilUuid(text(declaration, "versionId"), "declaration versionId"); + if (!tenantId.equals(draft.target().canonicalTenantId()) + || !versionId.equals(draft.target().canonicalVersionId())) { + throw new IllegalArgumentException("Original World graph declaration has another scope"); + } + JsonNode selector = declaration.get("startLocation"); + fields(selector, ROOM_TEMPLATE_REF_FIELDS); + UUID selectorTenant = + parseCanonicalNonNilUuid(text(selector, "tenantId"), "start selector tenantId"); + UUID selectorVersion = + parseCanonicalNonNilUuid(text(selector, "versionId"), "start selector versionId"); + UUID roomTemplateId = + parseCanonicalNonNilUuid(text(selector, "roomTemplateId"), "start selector roomTemplateId"); + if (!tenantId.equals(selectorTenant) || !versionId.equals(selectorVersion)) { + throw new IllegalArgumentException("Original World start selector has another scope"); + } + JsonNode counts = declaration.get("familyCounts"); + if (counts == null || !counts.isArray() || counts.size() != FRESH_GRAPH_FAMILIES.size()) { + throw new IllegalArgumentException("Original World graph declaration is incomplete"); + } + for (int i = 0; i < FRESH_GRAPH_FAMILIES.size(); i++) { + JsonNode entry = counts.get(i); + fields(entry, FAMILY_COUNT_FIELDS); + String family = text(entry, "family"); + JsonNode countNode = entry.get("count"); + if (!FRESH_GRAPH_FAMILIES.get(i).equals(family) + || countNode == null + || !countNode.isIntegralNumber() + || !countNode.canConvertToInt() + || countNode.intValue() < 0) { + throw new IllegalArgumentException( + "Original World graph family counts must be present, ordered and nonnegative"); + } + int actualCount = + (int) nodes.values().stream().filter(node -> node.family().equals(family)).count(); + if (actualCount != countNode.intValue()) { + throw new IllegalArgumentException( + "Original World graph family count differs from its complete typed input"); + } + } + OriginalGraphNode selectedRoom = + nodes.get("WORLD_DESIGN_AGGREGATE_TYPE_ROOM:" + roomTemplateId); + if (selectedRoom == null) { + throw new IllegalArgumentException( + "Original World start selector is absent from its ROOM graph"); + } + return new OriginalFreshGraph( + tenantId, + versionId, + roomTemplateId, + selectedRoom, + Map.copyOf(nodes), + List.copyOf(nodes.values())); + } + + private static void validateDeclaredGraphRows( + JsonNode rows, + OriginalFreshGraph original, + String targetNamespace, + DraftAuthorizationFenceBinding binding, + UUID versionIdentityOperationId) { + if (rows.size() != original.nodes().size()) { + throw new IllegalArgumentException( + "World v2 graph rows differ from the complete original input"); + } + Set seenNodes = new HashSet<>(); + Set seenMappingIds = new HashSet<>(); + Set seenPrivateRowKeys = new HashSet<>(); + Long privateTenantId = null; + Long privateVersionId = null; + boolean selectedRoomFound = false; + int rowIndex = 0; + for (JsonNode row : rows) { + fields(row, GRAPH_ROW_FIELDS); + JsonNode mapping = row.get("mapping"); + fields(mapping, GRAPH_MAPPING_FIELDS); + if (row.get("content") == null || !row.get("content").isObject()) { + throw new IllegalArgumentException("World v2 graph row content is absent"); + } + exactText(mapping, "target_namespace", targetNamespace); + exactText(mapping, "canonical_tenant_id", binding.tenantId().toString()); + exactText(mapping, "canonical_version_id", binding.versionId().toString()); + exactText(mapping, "request_id", binding.requestId().toString()); + exactText(mapping, "commit_id", binding.commitId().toString()); + String family = text(mapping, "family"); + if (!FRESH_GRAPH_FAMILIES.contains("WORLD_DESIGN_AGGREGATE_TYPE_" + family)) { + throw new IllegalArgumentException("World v2 graph row has an unsupported family"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mapping, "template_id"), "graph template_id"); + String nodeKey = "WORLD_DESIGN_AGGREGATE_TYPE_" + family + ":" + templateId; + OriginalGraphNode originalNode = original.nodes().get(nodeKey); + if (originalNode == null + || !original.orderedNodes().get(rowIndex).equals(originalNode) + || !seenNodes.add(nodeKey) + || !originalNode.revisionId().toString().equals(text(mapping, "revision_id")) + || !originalNode.revisionOrder().equals(text(mapping, "revision_order"))) { + throw new IllegalArgumentException( + "World v2 graph row differs from its exact original revision"); + } + UUID graphVersionIdentityOperationId = + parseCanonicalNonNilUuid( + text(mapping, "version_identity_operation_id"), "graph Version identity operation"); + if (!versionIdentityOperationId.equals(graphVersionIdentityOperationId)) { + throw new IllegalArgumentException( + "World v2 graph uses another Version identity operation"); + } + long mappingId = positiveLong(mapping, "id"); + long tenantId = positiveLong(mapping, "tenant_id"); + long versionId = positiveLong(mapping, "version_id"); + long privateRowKey = positiveLong(mapping, "private_row_key"); + if (privateTenantId == null) { + privateTenantId = tenantId; + privateVersionId = versionId; + } else if (privateTenantId != tenantId || privateVersionId != versionId) { + throw new IllegalArgumentException( + "World v2 graph rows cross private tenant or Version scope"); + } + if (!seenMappingIds.add(mappingId) || !seenPrivateRowKeys.add(family + ":" + privateRowKey)) { + throw new IllegalArgumentException("World v2 graph contains a repeated private mapping"); + } + if (originalNode.equals(original.selectedRoom()) + && "ROOM".equals(family) + && templateId.equals(original.roomTemplateId())) { + selectedRoomFound = true; + } + rowIndex++; + } + if (!selectedRoomFound || seenNodes.size() != original.nodes().size()) { + throw new IllegalArgumentException("World v2 graph omits the exact selected ROOM row"); + } + } + + private static void validateStartLocationReceipt( + JsonNode result, + String graphDigest, + OriginalFreshGraph original, + WorldDraftTerminalReadEvidence.Request request, + DraftCommitBinding draft, + DraftAuthorizationFenceBinding binding) + throws NoSuchAlgorithmException { + var receipt = + WorldDraftStartLocationEvidence.fromStored(base64(result, "startLocationReceiptBase64")); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(binding.operationId()) + || !receipt.requestId().equals(binding.requestId()) + || !receipt.commitId().equals(binding.commitId()) + || !receipt.authorizationFenceId().equals(binding.fenceId()) + || !receipt.accountBindingDigest().equals(sha256(request.originalAccountBinding())) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(original.tenantId()) + || !receipt.startLocation().versionId().equals(original.versionId()) + || !receipt.startLocation().roomTemplateId().equals(original.roomTemplateId()) + || !receipt.graphDigest().equals(graphDigest)) { + throw new IllegalArgumentException( + "World start-location receipt differs from its original Account-bound graph"); + } + exactText(result, "startLocationReceiptDigest", receipt.receiptDigest()); + } + + private static long positiveLong(JsonNode value, String field) { + JsonNode actual = value.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw new IllegalArgumentException("World graph requires positive private mapping " + field); + } + return actual.longValue(); + } + + private static String text(JsonNode value, String field) { + JsonNode actual = value == null ? null : value.get(field); + if (actual == null || !actual.isTextual()) { + throw new IllegalArgumentException("World APPLIED carrier requires text " + field); + } + return actual.textValue(); + } + + private static void fieldsKnown(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) { + throw new IllegalArgumentException("Original World mutation has unsupported fields"); + } + } + + private record OriginalGraphNode( + String family, UUID templateId, UUID revisionId, String revisionOrder) {} + + private record OriginalFreshGraph( + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + OriginalGraphNode selectedRoom, + Map nodes, + List orderedNodes) {} + + private static void fields(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.size() != fields.size() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) + throw new IllegalArgumentException("World APPLIED carrier fields differ"); + } + + private static void exactText(JsonNode value, String field, String expected) { + if (value.get(field) == null + || !value.get(field).isTextual() + || !expected.equals(value.get(field).textValue())) + throw new IllegalArgumentException("World APPLIED carrier differs at " + field); + } + + private static String sha256(byte[] value) throws NoSuchAlgorithmException { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static byte[] base64(JsonNode value, String field) { + if (value.get(field) == null || !value.get(field).isTextual()) + throw new IllegalArgumentException("World APPLIED bytes missing"); + String encoded = value.get(field).textValue(); + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) + throw new IllegalArgumentException("Noncanonical World APPLIED Base64"); + return decoded; + } + + private static final class FrameReader { + private final ByteBuffer bytes; + + private FrameReader(byte[] value) { + bytes = ByteBuffer.wrap(value); + } + + private byte[] frame() { + if (bytes.remaining() < Integer.BYTES) + throw new IllegalArgumentException("Truncated World operation"); + int size = bytes.getInt(); + if (size <= 0 || size > bytes.remaining()) + throw new IllegalArgumentException("Invalid World operation frame"); + byte[] value = new byte[size]; + bytes.get(value); + return value; + } + + private String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(frame())) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Invalid World operation UTF-8", invalid); + } + } + + private void expect(String expected) { + if (!expected.equals(text())) + throw new IllegalArgumentException("Substituted World operation"); + } + + private void expectBytes(byte[] expected) { + if (!Arrays.equals(expected, frame())) + throw new IllegalArgumentException("Substituted World operation bytes"); + } + + private UUID canonicalUuid() { + return parseCanonicalNonNilUuid(text(), "World owner identity"); + } + + private void digest() { + if (!text().matches("(?:sha256:)?[0-9a-f]{64}")) + throw new IllegalArgumentException("Invalid World owner digest"); + } + + private void requireEnd() { + if (bytes.hasRemaining()) + throw new IllegalArgumentException("Trailing World operation bytes"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java new file mode 100644 index 0000000000..5a6be36581 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -0,0 +1,568 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Closed immutable launch binding evidence for an exact Game Design authored-world source. */ +public record AuthoredWorldLaunchDescriptorEvidence( + int schemaVersion, + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson, + String requestDigest, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId, + String resultDigest) { + public static final int SCHEMA_VERSION = 1; + private static final String REQUEST_DOMAIN = + "game-design-authored-world-launch-descriptor-request/v1"; + private static final String RESULT_DOMAIN = + "game-design-authored-world-launch-descriptor-result/v1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private record Field(String name, String value) {} + + /** The exact request values, including presence for every optional field. */ + public record Request( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson) { + public Request { + validateRequest( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public String requestDigest() { + return AuthoredWorldLaunchDescriptorEvidence.requestDigest(this); + } + } + + public AuthoredWorldLaunchDescriptorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world launch descriptor schema"); + } + Request request = + new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + requireOptional(scriptPatchVersionPresent, scriptPatchVersion, "scriptPatchVersion"); + requireOptional(remapSetIdPresent, remapSetId, "remapSetId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requirePositive(versionId, "versionId"); + requireText(runtimeFlagsJson, "runtimeFlagsJson"); + requireText(generationConfigRevision, "generationConfigRevision"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(requestDigest, "requestDigest"); + if (!request.requestDigest().equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the exact request tuple"); + } + requireDigest(resultDigest, "resultDigest"); + } + + /** Recomputes both closed digests after construction or deserialization. */ + public void requireValid() { + if (!requestDigest(this.request()).equals(requestDigest) + || !resultDigest(this).equals(resultDigest)) { + throw new IllegalArgumentException("Result digest does not match the immutable descriptor"); + } + } + + public Request request() { + return new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public static AuthoredWorldLaunchDescriptorEvidence create( + Request request, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence provisional = + new AuthoredWorldLaunchDescriptorEvidence( + SCHEMA_VERSION, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.authoredWorldSourceOperationId(), + request.authoredWorldSourceEvidenceDigest(), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson(), + request.requestDigest(), + launchDescriptorId, + versionId, + scriptPatchVersionPresent, + scriptPatchVersion, + runtimeFlagsJson, + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + remapSetIdPresent, + remapSetId, + "sha256:" + "0".repeat(64)); + AuthoredWorldLaunchDescriptorEvidence evidence = + new AuthoredWorldLaunchDescriptorEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.controlPlaneRequestId(), + provisional.canonicalTenantId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.gameTemplateId(), + provisional.requestedScriptPatchVersionPresent(), + provisional.requestedScriptPatchVersion(), + provisional.sourceVersionIdPresent(), + provisional.sourceVersionId(), + provisional.targetVersionIdPresent(), + provisional.targetVersionId(), + provisional.requestedRuntimeFlagsJsonPresent(), + provisional.requestedRuntimeFlagsJson(), + provisional.requestDigest(), + provisional.launchDescriptorId(), + provisional.versionId(), + provisional.scriptPatchVersionPresent(), + provisional.scriptPatchVersion(), + provisional.runtimeFlagsJson(), + provisional.generationConfigRevision(), + provisional.versionStateEpoch(), + provisional.releaseBundleId(), + provisional.publishedReleaseBundleRef(), + provisional.remapSetIdPresent(), + provisional.remapSetId(), + resultDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + public static String requestDigest(Request request) { + Objects.requireNonNull(request, "request"); + return digest( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Computes the result digest while deliberately excluding only {@code resultDigest}. */ + public static String resultDigest(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return digest( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + /** Returns the exact UTF-8 request preimage for shared producer and consumer proof. */ + public static byte[] requestPreimage(Request request) { + return preimage( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Returns the exact UTF-8 result preimage, excluding only the result digest itself. */ + public static byte[] resultPreimage(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return preimage( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + private static void validateRequest( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch, + boolean sourceVersionPresent, + Long sourceVersion, + boolean targetVersionPresent, + Long targetVersion, + boolean runtimeFlagsPresent, + String runtimeFlags) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + if (controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + if (strictUtf8(controlPlaneRequestId).length > 64) { + throw new IllegalArgumentException("controlPlaneRequestId exceeds its stored byte bound"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(sourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireOptional(requestedPatchPresent, requestedPatch, "requestedScriptPatchVersion"); + requireOptional(sourceVersionPresent, sourceVersion, "sourceVersionId"); + if (sourceVersionPresent) { + requirePositive(sourceVersion, "sourceVersionId"); + } + requireOptional(targetVersionPresent, targetVersion, "targetVersionId"); + if (targetVersionPresent) { + requirePositive(targetVersion, "targetVersionId"); + } + requireOptional(runtimeFlagsPresent, runtimeFlags, "requestedRuntimeFlagsJson"); + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static String digest(String domain, Field... fields) { + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(domain, fields))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + strictUtf8(value); + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java new file mode 100644 index 0000000000..b58a5b34d1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -0,0 +1,732 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Closed immutable full release-attestation evidence for an authored-world launch. */ +public record AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest, + @JsonInclude(JsonInclude.Include.NON_NULL) + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public static final int SCHEMA_VERSION = 1; + public static final int SELECTOR_SCHEMA_VERSION = 2; + private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; + private static final String SELECTOR_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v2"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final List PARTICIPANT_ORDER = + List.of( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + private static final Map SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS = + Map.of( + "WORLD_MANAGEMENT", 3, + "ENTITY_MANAGEMENT", 2, + "GAME_LOGIC", 1, + "AUTOMATION_SCRIPTING", 5, + "GAME_DESIGN_CONTROL_PLANE", 1); + private static final Comparator UNSIGNED_UTF8_ORDER = + AuthoredWorldReleaseAttestationEvidence::compareUnsignedUtf8; + + private record Field(String name, String value) {} + + /** Returns the required full-Version participant owner order. */ + public static List requiredParticipantOrder() { + return PARTICIPANT_ORDER; + } + + /** Returns the one supported digest schema for a required participant owner. */ + public static int supportedParticipantDigestSchema(String participantKey) { + Objects.requireNonNull(participantKey, "participantKey"); + Integer version = SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS.get(participantKey); + if (version == null) { + throw new IllegalArgumentException("Unsupported full-Version participant owner"); + } + return version; + } + + /** One successful, immutable owner digest included in the release attestation. */ + public record Participant( + String participantKey, + String scopeValue, + boolean baseVersionIdPresent, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + boolean abilitySchemaDigestPresent, + String abilitySchemaDigest) { + public Participant { + requireText(participantKey, "participantKey"); + requireText(scopeValue, "scopeValue"); + requireOptional(baseVersionIdPresent, baseVersionId, "baseVersionId"); + if (baseVersionIdPresent) { + requirePositive(baseVersionId, "baseVersionId"); + } + requireText(appliedCommitId, "appliedCommitId"); + requireParticipantContentDigest(contentDigest); + requirePositiveSchema(digestSchemaVersion, "digestSchemaVersion"); + requireOptional(abilitySchemaDigestPresent, abilitySchemaDigest, "abilitySchemaDigest"); + if (abilitySchemaDigestPresent) { + requireDigest(abilitySchemaDigest, "abilitySchemaDigest"); + } + } + } + + /** One content-addressed artifact included in the immutable release manifest. */ + public record Artifact( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + public Artifact { + requireText(usageKey, "usageKey"); + requireText(artifactKind, "artifactKind"); + requireText(immutableObjectKey, "immutableObjectKey"); + requireDigest(contentDigest, "contentDigest"); + requireText(contentType, "contentType"); + requireSupportedSchema(artifactSchemaVersion, "artifactSchemaVersion"); + String digestHex = contentDigest.substring("sha256:".length()); + String expectedObjectKey = "artifacts/sha256/" + digestHex; + if (!expectedObjectKey.equals(immutableObjectKey)) { + throw new IllegalArgumentException( + "immutableObjectKey must be the content-addressed key for contentDigest"); + } + } + } + + public AuthoredWorldReleaseAttestationEvidence { + if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(authoredWorldSourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(authoredWorldSourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(commitId, "commitId"); + participantDigests = + List.copyOf(Objects.requireNonNull(participantDigests, "participantDigests")); + validateParticipants(participantDigests, commitId); + requireDigest(manifestHash, "manifestHash"); + requireSupportedSchema(manifestSchemaVersion, "manifestSchemaVersion"); + requiredManifestAssetKeys = + List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys, "requiredManifestAssetKeys")); + validateOrderedUniqueStrings(requiredManifestAssetKeys, "requiredManifestAssetKeys"); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests, "artifactDigests")); + validateArtifacts(artifactDigests, requiredManifestAssetKeys); + commandDefinitions = + List.copyOf(Objects.requireNonNull(commandDefinitions, "commandDefinitions")); + for (String commandDefinition : commandDefinitions) { + strictUtf8(Objects.requireNonNull(commandDefinition, "commandDefinition")); + } + requireText(generationConfigRevision, "generationConfigRevision"); + requireDigest(evidenceDigest, "evidenceDigest"); + if ((schemaVersion == SELECTOR_SCHEMA_VERSION) != (worldStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Only release-attestation/v2 requires World selector evidence"); + } + if (worldStartLocationEvidence != null) { + WorldPublishedStartLocationEvidence.fromStored(worldStartLocationEvidence.canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + var world = participantDigests.getFirst(); + if (!targetNamespace.equals(selected.targetNamespace()) + || !canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId()) + || !commitId.equals(selected.appliedCommitId()) + || !world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException( + "World selector differs from the exact attested release checkpoint"); + } + } + } + + /** Original v1 constructor: retained bytes never gain a selector. */ + public AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest) { + this( + schemaVersion, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + evidenceDigest, + null); + } + + /** Creates v2 from the exact unchanged World evidence retained in the immutable release. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + Objects.requireNonNull(worldStartLocationEvidence, "worldStartLocationEvidence"); + var provisional = + new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64), + worldStartLocationEvidence); + return new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + computeEvidenceDigest(provisional), + worldStartLocationEvidence); + } + + /** Creates evidence from the complete owner attestation and derives its evidence digest. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision) { + AuthoredWorldReleaseAttestationEvidence provisional = + new AuthoredWorldReleaseAttestationEvidence( + SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64)); + AuthoredWorldReleaseAttestationEvidence evidence = + new AuthoredWorldReleaseAttestationEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.descriptorResultDigest(), + provisional.canonicalTenantId(), + provisional.canonicalVersionId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.launchDescriptorId(), + provisional.publishedReleaseBundleRef(), + provisional.versionStateEpoch(), + provisional.publishWorkflowId(), + provisional.commitId(), + provisional.participantDigests(), + provisional.manifestHash(), + provisional.manifestSchemaVersion(), + provisional.requiredManifestAssetKeys(), + provisional.artifactDigests(), + provisional.commandDefinitions(), + provisional.generationConfigRevision(), + computeEvidenceDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + /** Recomputes the closed evidence digest after construction or deserialization. */ + public void requireValid() { + if (!computeEvidenceDigest(this).equals(evidenceDigest)) { + throw new IllegalArgumentException( + "Evidence digest does not match the exact release attestation"); + } + } + + /** Recomputes both closed digests and binds every applicable descriptor field exactly. */ + public void requireValid(AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(descriptor, "descriptor"); + requireValid(); + descriptor.requireValid(); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !authoredWorldSourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !authoredWorldSourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !generationConfigRevision.equals(descriptor.generationConfigRevision())) { + throw new IllegalArgumentException( + "Release attestation does not match the exact launch descriptor binding"); + } + String descriptorVersionScope = Long.toString(descriptor.versionId()); + for (Participant participant : participantDigests) { + if (!descriptorVersionScope.equals(participant.scopeValue())) { + throw new IllegalArgumentException( + "Participant scope does not match the launch descriptor Version"); + } + } + } + + /** Computes the digest using the schema-specific domain and exhaustive field order. */ + public static String computeEvidenceDigest(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return "sha256:" + HexFormat.of().formatHex(sha256(evidencePreimage(evidence))); + } + + /** Returns the exact strict-UTF-8 preimage for cross-language codec proof. */ + public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + List fields = new ArrayList<>(); + fields.add(field("schemaVersion", Integer.toString(evidence.schemaVersion()))); + fields.add(field("targetNamespace", evidence.targetNamespace())); + fields.add(field("descriptorResultDigest", evidence.descriptorResultDigest())); + fields.add(field("canonicalTenantId", evidence.canonicalTenantId().toString())); + fields.add(field("canonicalVersionId", evidence.canonicalVersionId().toString())); + fields.add(field("worldSlug", evidence.worldSlug())); + fields.add( + field( + "authoredWorldSourceOperationId", + evidence.authoredWorldSourceOperationId().toString())); + fields.add( + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest())); + fields.add(field("launchDescriptorId", evidence.launchDescriptorId())); + fields.add(field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef())); + fields.add(field("versionStateEpoch", Long.toString(evidence.versionStateEpoch()))); + fields.add(field("publishWorkflowId", evidence.publishWorkflowId())); + fields.add(field("commitId", evidence.commitId())); + fields.add( + field("participantDigests.size", Integer.toString(evidence.participantDigests().size()))); + for (int index = 0; index < evidence.participantDigests().size(); index++) { + Participant participant = evidence.participantDigests().get(index); + String prefix = "participantDigests[" + index + "]."; + fields.add(field(prefix + "participantKey", participant.participantKey())); + fields.add(field(prefix + "scopeValue", participant.scopeValue())); + fields.add(optionalPresence(prefix + "baseVersionId", participant.baseVersionIdPresent())); + fields.add( + optionalValue( + prefix + "baseVersionId", + participant.baseVersionIdPresent(), + decimal(participant.baseVersionId()))); + fields.add(field(prefix + "appliedCommitId", participant.appliedCommitId())); + fields.add(field(prefix + "contentDigest", participant.contentDigest())); + fields.add( + field( + prefix + "digestSchemaVersion", Integer.toString(participant.digestSchemaVersion()))); + fields.add( + optionalPresence( + prefix + "abilitySchemaDigest", participant.abilitySchemaDigestPresent())); + fields.add( + optionalValue( + prefix + "abilitySchemaDigest", + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())); + } + fields.add(field("manifestHash", evidence.manifestHash())); + fields.add(field("manifestSchemaVersion", Integer.toString(evidence.manifestSchemaVersion()))); + fields.add( + field( + "requiredManifestAssetKeys.size", + Integer.toString(evidence.requiredManifestAssetKeys().size()))); + for (int index = 0; index < evidence.requiredManifestAssetKeys().size(); index++) { + fields.add( + field( + "requiredManifestAssetKeys[" + index + "]", + evidence.requiredManifestAssetKeys().get(index))); + } + fields.add(field("artifactDigests.size", Integer.toString(evidence.artifactDigests().size()))); + for (int index = 0; index < evidence.artifactDigests().size(); index++) { + Artifact artifact = evidence.artifactDigests().get(index); + String prefix = "artifactDigests[" + index + "]."; + fields.add(field(prefix + "usageKey", artifact.usageKey())); + fields.add(field(prefix + "artifactKind", artifact.artifactKind())); + fields.add(field(prefix + "immutableObjectKey", artifact.immutableObjectKey())); + fields.add(field(prefix + "contentDigest", artifact.contentDigest())); + fields.add(field(prefix + "contentType", artifact.contentType())); + fields.add( + field( + prefix + "artifactSchemaVersion", + Integer.toString(artifact.artifactSchemaVersion()))); + } + fields.add( + field("commandDefinitions.size", Integer.toString(evidence.commandDefinitions().size()))); + for (int index = 0; index < evidence.commandDefinitions().size(); index++) { + fields.add( + field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); + } + fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); + if (evidence.schemaVersion() == SELECTOR_SCHEMA_VERSION) { + fields.add( + field( + "worldStartLocationEvidence.canonicalBytesBase64", + Base64.getEncoder() + .encodeToString(evidence.worldStartLocationEvidence().canonicalBytes()))); + } + return preimage( + evidence.schemaVersion() == SCHEMA_VERSION ? EVIDENCE_DOMAIN : SELECTOR_EVIDENCE_DOMAIN, + fields.toArray(Field[]::new)); + } + + private static void validateParticipants(List participants, String commitId) { + if (participants.size() != PARTICIPANT_ORDER.size()) { + throw new IllegalArgumentException( + "A complete attestation requires exactly five participants"); + } + for (int index = 0; index < PARTICIPANT_ORDER.size(); index++) { + Participant participant = + Objects.requireNonNull(participants.get(index), "participantDigest"); + String expectedKey = PARTICIPANT_ORDER.get(index); + if (!expectedKey.equals(participant.participantKey())) { + throw new IllegalArgumentException("Participant digests are not in canonical owner order"); + } + if (supportedParticipantDigestSchema(participant.participantKey()) + != participant.digestSchemaVersion()) { + throw new IllegalArgumentException( + "Participant digest schema is unsupported for its owner"); + } + if (participant.baseVersionIdPresent()) { + throw new IllegalArgumentException( + "Full-Version participants must not have a baseVersionId"); + } + if (participant.scopeValue() == null + || !CANONICAL_POSITIVE_DECIMAL.matcher(participant.scopeValue()).matches()) { + throw new IllegalArgumentException( + "Full-Version participant scope must be a positive decimal Version"); + } + try { + if (Long.parseLong(participant.scopeValue()) <= 0) { + throw new IllegalArgumentException("Participant scope must be positive"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Participant scope must fit a positive Version id", exception); + } + if (!commitId.equals(participant.appliedCommitId())) { + throw new IllegalArgumentException("Every participant must report the attested commitId"); + } + boolean requiresAbilityDigest = "GAME_LOGIC".equals(participant.participantKey()); + if (participant.abilitySchemaDigestPresent() != requiresAbilityDigest) { + throw new IllegalArgumentException( + "Only GAME_LOGIC may supply the dedicated ability-schema digest"); + } + } + } + + private static void validateOrderedUniqueStrings(List values, String name) { + String previous = null; + for (String value : values) { + Objects.requireNonNull(value, name + " entry"); + requireText(value, name + " entry"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, value) >= 0) { + throw new IllegalArgumentException(name + " must be unique and unsigned-UTF-8 ordered"); + } + previous = value; + } + } + + private static void validateArtifacts(List artifacts, List requiredKeys) { + String previous = null; + Map byUsageKey = new java.util.HashMap<>(); + for (Artifact artifact : artifacts) { + Objects.requireNonNull(artifact, "artifactDigest"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, artifact.usageKey()) >= 0) { + throw new IllegalArgumentException( + "artifactDigests must be unique and unsigned-UTF-8 ordered"); + } + previous = artifact.usageKey(); + byUsageKey.put(artifact.usageKey(), artifact); + } + for (String requiredKey : requiredKeys) { + if (!byUsageKey.containsKey(requiredKey)) { + throw new IllegalArgumentException("Every required manifest key must select an artifact"); + } + } + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static int compareUnsignedUtf8(String left, String right) { + byte[] leftBytes = strictUtf8(left); + byte[] rightBytes = strictUtf8(right); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int difference = Byte.toUnsignedInt(leftBytes[index]) - Byte.toUnsignedInt(rightBytes[index]); + if (difference != 0) { + return difference; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireSupportedSchema(int value, String name) { + if (value != SCHEMA_VERSION) { + throw new IllegalArgumentException(name + " is unsupported"); + } + } + + private static void requirePositiveSchema(int value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + strictUtf8(value); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireParticipantContentDigest(String value) { + Objects.requireNonNull(value, "contentDigest"); + if (!PARTICIPANT_CONTENT_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException( + "Participant contentDigest must be 64 lowercase hexadecimal characters"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java new file mode 100644 index 0000000000..8b6089e638 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.Objects; + +/** The exact independently validated descriptor and release-attestation pair for a launch. */ +public record CompleteLaunchBindingEvidence( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingEvidence { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + releaseAttestation.requireValid(descriptor); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java new file mode 100644 index 0000000000..a562ded108 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; + +/** Explicit mTLS client for the exact Game Design publication terminal read. */ +public final class GameDesignPublicationTerminalClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignPublicationTerminalClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameDesignPublicationTerminalClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Account or World service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design publication terminal client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design publication terminal client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads and validates Game Design-owned publication terminal evidence for this exact canonical + * request. + */ + public GameDesignPublicationTerminalReadEvidence.ReadResult read( + GameDesignPublicationTerminalReadEvidence.ReadRequest request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design publication terminal request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); + try { + return GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid publication terminal read evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignPublicationTerminalReadServiceGrpc.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 GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design publication terminal client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java new file mode 100644 index 0000000000..f83405fcb5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Immutable original owner result. Decoding establishes integrity, never transport authority. */ +public final class GameDesignPublicationTerminalEvidence { + public static final String SCHEMA = "game-design-publication-terminal/v1"; + public static final String RELEASE_SCHEMA = "game-design-published-release-bundle/v1"; + + public enum Outcome { + PUBLISHED, + NO_PUBLICATION + } + + /** Lossless participant content, including the presence of nullable publication result fields. */ + public record Participant( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String abilitySchemaDigest, + String errorCode, + String errorMessage) { + public Participant { + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + scopeValue, + baseVersionId != null, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + abilitySchemaDigest != null, + abilitySchemaDigest); + if (errorCode != null && !errorCode.isEmpty()) { + throw new IllegalArgumentException("Published participant cannot carry an error"); + } + if (errorMessage != null) utf8(errorMessage); + } + } + + /** Complete full-Version content; private SQL aliases and publishedAt are excluded. */ + public record ReleaseContent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + int manifestSchemaVersion, + List artifactDigests, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public ReleaseContent { + uuid(canonicalTenantId); + uuid(canonicalVersionId); + text(publishedReleaseBundleRef); + text(publishWorkflowId); + text(generationConfigRevision); + if (versionNumber <= 0 + || !"v2".equals(attestationSchemaVersion) + || manifestSchemaVersion != 1) { + throw new IllegalArgumentException("Complete full-Version bundle/v2 required"); + } + digest(manifestHash); + artifactDigests = List.copyOf(artifactDigests); + requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys); + participantDigests = List.copyOf(participantDigests); + commandDefinitions = List.copyOf(commandDefinitions); + commandDefinitions.forEach(GameDesignPublicationTerminalEvidence::utf8); + worldStartLocationEvidence = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(worldStartLocationEvidence).canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + if (!canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId())) { + throw new IllegalArgumentException("Release identity differs from World checkpoint"); + } + var owners = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (participantDigests.size() != owners.size()) { + throw new IllegalArgumentException("Exactly five participant owners required"); + } + for (int i = 0; i < owners.size(); i++) { + var p = participantDigests.get(i); + if (!owners.get(i).equals(p.participantKey()) + || p.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey()) + || p.baseVersionId() != null + || !selected.appliedCommitId().equals(p.appliedCommitId()) + || !p.scopeValue().matches("[1-9][0-9]*") + || new BigInteger(p.scopeValue()).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 + || ((p.abilitySchemaDigest() != null) != "GAME_LOGIC".equals(p.participantKey()))) { + throw new IllegalArgumentException("Incomplete or changed required participant proof"); + } + } + var world = participantDigests.getFirst(); + if (!world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException("World participant differs from frozen checkpoint"); + } + ordered(requiredManifestAssetKeys); + ordered( + artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList()); + if (!artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList() + .containsAll(requiredManifestAssetKeys)) { + throw new IllegalArgumentException( + "Every required asset must have actual-byte artifact proof"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + segment(out, RELEASE_SCHEMA); + segment(out, canonicalTenantId.toString()); + segment(out, canonicalVersionId.toString()); + segment(out, publishedReleaseBundleRef); + segment(out, Integer.toString(versionNumber)); + segment(out, attestationSchemaVersion); + segment(out, publishWorkflowId); + segment(out, manifestHash); + segment(out, Integer.toString(manifestSchemaVersion)); + segment(out, Integer.toString(artifactDigests.size())); + for (var a : artifactDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, a.usageKey()); + segment(entry, a.artifactKind()); + segment(entry, a.immutableObjectKey()); + segment(entry, a.contentDigest()); + segment(entry, a.contentType()); + segment(entry, Integer.toString(a.artifactSchemaVersion())); + segment(out, entry.toByteArray()); + } + strings(out, requiredManifestAssetKeys); + segment(out, Integer.toString(participantDigests.size())); + for (var p : participantDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, p.participantKey()); + segment(entry, p.scopeValue()); + optional(entry, p.baseVersionId() == null ? null : p.baseVersionId().toString()); + segment(entry, p.appliedCommitId()); + segment(entry, p.contentDigest()); + segment(entry, Integer.toString(p.digestSchemaVersion())); + optional(entry, p.abilitySchemaDigest()); + optional(entry, p.errorCode()); + optional(entry, p.errorMessage()); + segment(out, entry.toByteArray()); + } + strings(out, commandDefinitions); + segment(out, generationConfigRevision); + segment(out, worldStartLocationEvidence.canonicalBytes()); + // Full versions cannot carry a script patch; explicit presence is still part of content. + segment(out, "false"); + optional(out, null); + return out.toByteArray(); + } + + public String contentDigest() { + return sha256(canonicalBytes()); + } + + public static ReleaseContent fromStored(byte[] bytes) { + var r = new Reader(bytes); + r.expect(RELEASE_SCHEMA); + UUID tenant = UUID.fromString(r.text()); + UUID version = UUID.fromString(r.text()); + String ref = r.text(); + int number = r.positiveInt(); + String schema = r.text(); + String workflow = r.text(); + String manifest = r.text(); + int manifestSchema = r.positiveInt(); + var artifacts = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var a = new Reader(r.bytes()); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + a.text(), a.text(), a.text(), a.text(), a.text(), a.positiveInt())); + a.end(); + } + List required = r.strings(); + var participants = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var p = new Reader(r.bytes()); + String owner = p.text(); + String scope = p.text(); + String base = p.optional(); + participants.add( + new Participant( + owner, + scope, + base == null ? null : positiveLong(base), + p.text(), + p.text(), + p.positiveInt(), + p.optional(), + p.optional(), + p.optional())); + p.end(); + } + List commands = r.strings(); + String generation = r.text(); + var world = WorldPublishedStartLocationEvidence.fromStored(r.bytes()); + r.expect("false"); + if (r.optional() != null) throw new IllegalArgumentException("Full version has script patch"); + r.end(); + var result = + new ReleaseContent( + tenant, + version, + ref, + number, + schema, + workflow, + manifest, + manifestSchema, + artifacts, + required, + participants, + commands, + generation, + world); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical release content"); + return result; + } + } + + private final GameDesignPublicationOperationBinding operation; + private final Outcome outcome; + private final ReleaseContent release; + private final Long epoch; + + public GameDesignPublicationTerminalEvidence( + byte[] operationBytes, + Outcome outcome, + ReleaseContent release, + Long publicationVersionStateEpoch) { + this.operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + this.outcome = Objects.requireNonNull(outcome); + if ((outcome == Outcome.PUBLISHED) != (release != null && publicationVersionStateEpoch != null) + || (outcome == Outcome.NO_PUBLICATION + && (release != null || publicationVersionStateEpoch != null))) { + throw new IllegalArgumentException("Outcome-inapplicable release or epoch"); + } + this.release = release == null ? null : ReleaseContent.fromStored(release.canonicalBytes()); + this.epoch = publicationVersionStateEpoch; + if (release != null) { + if (epoch <= 0 + || epoch != Math.addExact(operation.world().request().versionStateEpoch(), 1L) + || !Arrays.equals( + release.worldStartLocationEvidence().canonicalBytes(), + operation.world().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal release differs from original publication operation"); + } + String scope = + Long.toString(operation.account().input().selection().target().gameDesignVersionRowId()); + if (release.participantDigests().stream().anyMatch(p -> !scope.equals(p.scopeValue()))) { + throw new IllegalArgumentException("Participant scope differs from selected owner Version"); + } + } + } + + public Outcome outcome() { + return outcome; + } + + public byte[] operationBytes() { + return operation.canonicalBytes(); + } + + public WorldPublishedStartLocationEvidence worldEvidence() { + return operation.world(); + } + + public String publishedReleaseBundleRef() { + return requireRelease().publishedReleaseBundleRef(); + } + + public String publishedReleaseBundleDigest() { + return requireRelease().contentDigest(); + } + + public long publicationVersionStateEpoch() { + requireRelease(); + return epoch; + } + + public ReleaseContent releaseContent() { + return requireRelease(); + } + + private ReleaseContent requireRelease() { + if (release == null) + throw new IllegalStateException( + "NO_PUBLICATION has no release or committed publication epoch"); + return release; + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome.name()); + if (release != null) { + DraftAuthorizationFenceBinding.frame(out, release.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Long.toString(epoch)); + } + return out.toByteArray(); + } + + public static GameDesignPublicationTerminalEvidence fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + byte[] operation = r.bytes(); + Outcome outcome = Outcome.valueOf(r.text()); + ReleaseContent release = + outcome == Outcome.PUBLISHED ? ReleaseContent.fromStored(r.bytes()) : null; + Long epoch = outcome == Outcome.PUBLISHED ? positiveLong(r.text()) : null; + r.requireEnd(); + var result = new GameDesignPublicationTerminalEvidence(operation, outcome, release, epoch); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal evidence"); + return result; + } + + private static void uuid(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + private static void text(String s) { + if (s == null || s.isBlank() || s.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Canonical nonblank text required"); + utf8(s); + } + + private static void digest(String s) { + if (s == null || !s.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA256 digest required"); + } + + private static long positiveLong(String s) { + if (!s.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Canonical positive decimal required"); + try { + return Long.parseLong(s); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Counter exceeds owner range", e); + } + } + + private static byte[] utf8(String s) { + try { + var b = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(Objects.requireNonNull(s))); + var bytes = new byte[b.remaining()]; + b.get(bytes); + return bytes; + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + private static void ordered(List values) { + String prior = null; + for (String value : values) { + text(value); + if (prior != null && Arrays.compareUnsigned(utf8(prior), utf8(value)) >= 0) + throw new IllegalArgumentException("Array must be unique and unsigned UTF-8 ordered"); + prior = value; + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static void segment(ByteArrayOutputStream out, String value) { + segment(out, utf8(value)); + } + + private static void segment(ByteArrayOutputStream out, byte[] bytes) { + out.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + out.write(':'); + out.writeBytes(bytes); + } + + private static void optional(ByteArrayOutputStream out, String value) { + segment(out, value == null ? "false" : "true"); + segment(out, value == null ? "" : value); + } + + private static void strings(ByteArrayOutputStream out, List values) { + segment(out, Integer.toString(values.size())); + values.forEach(v -> segment(out, v)); + } + + private static final class Reader { + private final byte[] bytes; + private int offset; + + Reader(byte[] bytes) { + this.bytes = Objects.requireNonNull(bytes).clone(); + } + + byte[] bytes() { + int start = offset; + while (offset < bytes.length && bytes[offset] >= '0' && bytes[offset] <= '9') offset++; + if (start == offset || offset == bytes.length || bytes[offset] != ':') + throw new IllegalArgumentException("Malformed byte-length frame"); + String decimal = new String(bytes, start, offset - start, StandardCharsets.US_ASCII); + if (!decimal.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical frame length"); + int length; + try { + length = new BigInteger(decimal).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Frame too large", e); + } + offset++; + if (length > bytes.length - offset) throw new IllegalArgumentException("Truncated frame"); + byte[] value = Arrays.copyOfRange(bytes, offset, offset + length); + offset += length; + return value; + } + + String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes())) + .toString(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + void expect(String value) { + if (!value.equals(text())) throw new IllegalArgumentException("Unexpected canonical field"); + } + + int positiveInt() { + return Math.toIntExact(positiveLong(text())); + } + + int count() { + String s = text(); + if (!s.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical array count"); + int n; + try { + n = new BigInteger(s).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Array too large", e); + } + if (n > (bytes.length - offset) / 2) throw new IllegalArgumentException("Incomplete array"); + return n; + } + + String optional() { + String present = text(); + String value = text(); + if ("true".equals(present)) return value; + if (!"false".equals(present) || !value.isEmpty()) + throw new IllegalArgumentException("Malformed optional field"); + return null; + } + + List strings() { + var result = new ArrayList(); + for (int n = count(); n > 0; n--) result.add(text()); + return result; + } + + void end() { + if (offset != bytes.length) throw new IllegalArgumentException("Trailing fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java new file mode 100644 index 0000000000..d88b0fdb69 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; + +/** + * Closed immutable read correlation. Integrity alone grants no settlement or workload authority. + */ +public final class GameDesignPublicationTerminalReadEvidence { + private GameDesignPublicationTerminalReadEvidence() {} + + public enum Status { + UNKNOWN, + PUBLISHED, + NO_PUBLICATION + } + + public record ReadRequest( + int schemaVersion, String targetNamespace, UUID readRequestId, byte[] operationBytes) { + public static final int SCHEMA_VERSION = 1; + public static final String SCHEMA = "game-design-publication-terminal-read-request/v1"; + + public ReadRequest { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || readRequestId == null + || readRequestId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException( + "Closed schema-1 namespace and non-nil read UUID required"); + } + operationBytes = + GameDesignPublicationOperationBinding.fromStored(operationBytes).canonicalBytes(); + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Read namespace differs from original World operation"); + } + if (readRequestId.equals(operation.account().operationId()) + || readRequestId.equals(operation.account().fenceId()) + || readRequestId.equals(operation.world().request().intakeRequestId()) + || readRequestId.equals(operation.world().request().publicationFence()) + || readRequestId.toString().equals(operation.world().request().publicationRequestId()) + || readRequestId.equals( + operation.account().input().selection().intent().selectedCommitRequestId()) + || readRequestId.equals( + operation.account().input().selection().intent().selectedCommitId())) { + throw new IllegalArgumentException( + "Terminal read UUID must be distinct from original operation identity"); + } + } + + public static ReadRequest create(String namespace, byte[] operationBytes) { + return new ReadRequest(SCHEMA_VERSION, namespace, UUID.randomUUID(), operationBytes); + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(schemaVersion)); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + DraftAuthorizationFenceBinding.frame(out, readRequestId.toString()); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + return out.toByteArray(); + } + + public static ReadRequest fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + r.expect("1"); + var result = new ReadRequest(1, r.text(), UUID.fromString(r.text()), r.bytes()); + r.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal read request"); + return result; + } + } + + public record ReadResult( + ReadRequest request, + Status status, + Optional terminalEvidence) { + public static final String SCHEMA = "game-design-publication-terminal-read-response/v1"; + + public ReadResult { + request = ReadRequest.fromStored(Objects.requireNonNull(request).canonicalBytes()); + Objects.requireNonNull(status); + Objects.requireNonNull(terminalEvidence); + if ((status == Status.UNKNOWN) != terminalEvidence.isEmpty()) { + throw new IllegalArgumentException("UNKNOWN alone omits terminal evidence"); + } + if (terminalEvidence.isPresent()) { + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + terminalEvidence.orElseThrow().canonicalBytes()); + if (!terminal.outcome().name().equals(status.name()) + || !Arrays.equals(request.operationBytes(), terminal.operationBytes())) { + throw new IllegalArgumentException( + "Terminal result differs from exact original read operation or outcome"); + } + terminalEvidence = Optional.of(terminal); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, request.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, status.name()); + terminalEvidence.ifPresent( + t -> DraftAuthorizationFenceBinding.frame(out, t.canonicalBytes())); + return out.toByteArray(); + } + + public static ReadResult fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + var request = ReadRequest.fromStored(r.bytes()); + var status = Status.valueOf(r.text()); + var terminal = + status == Status.UNKNOWN + ? Optional.empty() + : Optional.of(GameDesignPublicationTerminalEvidence.fromStored(r.bytes())); + r.requireEnd(); + var result = new ReadResult(request, status, terminal); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal read response"); + return result; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..4cb2c9abbc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; + +/** Closed wire mapping; receiver authentication must precede decoding. */ +public final class GameDesignPublicationTerminalReadGrpcCodec { + private GameDesignPublicationTerminalReadGrpcCodec() {} + + public static ReadGameDesignPublicationTerminalRequest toRequest(ReadRequest request) { + return ReadGameDesignPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(Objects.requireNonNull(request).canonicalBytes())) + .build(); + } + + public static ReadRequest fromRequest(ReadGameDesignPublicationTerminalRequest request) { + if (!Objects.requireNonNull(request).getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read request required"); + } + return ReadRequest.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + public static ReadGameDesignPublicationTerminalResponse toResponse( + ReadRequest request, ReadResult result) { + exact(request, result); + return ReadGameDesignPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(result.canonicalBytes())) + .build(); + } + + public static ReadResult fromResponse( + ReadRequest request, ReadGameDesignPublicationTerminalResponse response) { + if (!Objects.requireNonNull(response).getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read response required"); + } + var result = ReadResult.fromStored(response.getCanonicalResponseBytes().toByteArray()); + exact(request, result); + return result; + } + + private static void exact(ReadRequest request, ReadResult result) { + if (!Arrays.equals( + Objects.requireNonNull(request).canonicalBytes(), + Objects.requireNonNull(result).request().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal read response changed the complete request echo"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java new file mode 100644 index 0000000000..a53c0b5511 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.util.concurrent.Executor; + +/** Authenticates the exact server workload before gRPC releases request headers or body. */ +public final class GrpcServerPeerIdentityCallCredentials extends CallCredentials { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + var sslSession = + requestInfo == null || requestInfo.getTransportAttrs() == null + ? null + : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + boolean exactPeer = + GrpcPeerIdentity.fromSslSession(sslSession) + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false); + if (!exactPeer) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Request requires the exact authenticated server workload identity")); + return; + } + applier.apply(new Metadata()); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java new file mode 100644 index 0000000000..8d4257ef55 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; + +/** + * Distinct publication operation's immutable original input and Account source participation. This + * validates complete selected Draft structure, not actor authentication or positive source + * authority. The future Account producer must independently establish the complete current source + * vector, including party and operative hosted terms. Draft COMMIT_ORDER and creation results never + * authorize or settle this operation. Later World captures and release/artifact results remain + * separate and must never rewrite the original selection digest. + */ +public record AccountPublicationAuthorizationBinding( + UUID operationId, UUID fenceId, PreallocationInput input, List sources) { + public static final String SCHEMA = "account-publication-authorization/v1"; + + public AccountPublicationAuthorizationBinding { + DraftAuthorizationFenceBinding.requireUuid(operationId); + DraftAuthorizationFenceBinding.requireUuid(fenceId); + Objects.requireNonNull(input); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct applicable publication sources required"); + } + for (SourceEvidence source : sources) { + String requiredScope = + switch (source.kind()) { + case ACCOUNT, GLOBAL_ROLES -> input.actorAccountId().toString(); + case TENANT -> input.selection().intent().canonicalTenantId().toString(); + case MEMBERSHIP -> + input.actorAccountId() + "/" + input.selection().intent().canonicalTenantId(); + default -> null; + }; + if (requiredScope != null && !requiredScope.equals(source.scopeId())) { + throw new IllegalArgumentException( + "Publication source differs from exact actor/tenant scope"); + } + } + } + + /** Stable caller/selection inputs, before any Account operation/fence or World allocation. */ + public record PreallocationInput( + UUID actorAccountId, AuthoredDraftPublishSelectionBinding selection) { + public PreallocationInput { + DraftAuthorizationFenceBinding.requireUuid(actorAccountId); + Objects.requireNonNull(selection); + // Reconstruct the whole closed selection, including target, commit and synchronized fence. + selection = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-publication-input/v1"); + DraftAuthorizationFenceBinding.frame(out, actorAccountId.toString()); + DraftAuthorizationFenceBinding.frame(out, selection.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selection.digest()); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + } + + public UUID tenantId() { + return input.selection().intent().canonicalTenantId(); + } + + public String publishRequestId() { + return input.selection().intent().publishRequestId(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationId.toString()); + DraftAuthorizationFenceBinding.frame(out, fenceId.toString()); + DraftAuthorizationFenceBinding.frame(out, input.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + return out.toByteArray(); + } + + public static AccountPublicationAuthorizationBinding fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect(SCHEMA); + UUID operationId = uuid(reader.text()); + UUID fenceId = uuid(reader.text()); + FrameReader inputReader = new FrameReader(reader.bytes()); + inputReader.expect("account-publication-input/v1"); + UUID actor = uuid(inputReader.text()); + byte[] selectionBytes = inputReader.bytes(); + String digest = inputReader.text(); + inputReader.requireEnd(); + var selection = + AuthoredDraftPublishSelectionBinding.fromStored( + new String(selectionBytes, StandardCharsets.UTF_8), digest); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + final int count; + try { + count = Integer.parseInt(countText); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Publication source count out of range", invalid); + } + if (count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete publication source vector"); + } + List sources = new ArrayList<>(); + for (int i = 0; i < count; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.requireEnd(); + var binding = + new AccountPublicationAuthorizationBinding( + operationId, fenceId, new PreallocationInput(actor, selection), sources); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication authorization binding"); + } + return binding; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java new file mode 100644 index 0000000000..9c1d742629 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable exact selection of an existing synchronized authored Draft for full-version + * publication. This is retained selection evidence, not authorization, owner freeze, or release + * evidence. + */ +public final class AuthoredDraftPublishSelectionBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final PublishIntent intent; + private final TargetProof target; + private final DraftCommitBinding selectedCommit; + private final UUID fenceRequestId; + private final UUID fenceCommitId; + private final String fenceInputDigest; + private final String fenceResultVectorJson; + private final String fenceCreatedAt; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredDraftPublishSelectionBinding( + PublishIntent intent, + TargetProof target, + DraftCommitBinding selectedCommit, + VisibilityFence fence) { + this.intent = Objects.requireNonNull(intent, "intent"); + this.target = Objects.requireNonNull(target, "target"); + this.selectedCommit = Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(fence, "fence"); + if (!intent.canonicalTenantId().equals(target.canonicalTenantId()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !target.equals(selectedCommit.target()) + || !intent.selectedCommitRequestId().equals(selectedCommit.requestId()) + || !intent.selectedCommitId().equals(selectedCommit.commitId()) + || !intent.selectedCommitDigest().equals(selectedCommit.digest()) + || !target.equals(fence.target()) + || !intent.selectedCommitRequestId().equals(fence.requestId()) + || !intent.selectedCommitId().equals(fence.commitId()) + || !intent.selectedCommitDigest().equals(fence.inputDigest())) { + throw new IllegalArgumentException( + "Authored Draft publication selection differs from its exact synchronized commit fence"); + } + requireCanonicalArray(fence.resultVectorJson()); + this.fenceRequestId = fence.requestId(); + this.fenceCommitId = fence.commitId(); + this.fenceInputDigest = fence.inputDigest(); + this.fenceResultVectorJson = fence.resultVectorJson(); + this.fenceCreatedAt = fence.createdAt().toInstant().toString(); + try { + canonicalBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Authored Draft publication selection could not be canonicalized", exception); + } + } + + /** + * Constructs the exact retained value after the repository has independently verified the locked + * Version, durable commit, owner result vector, and current visibility fence. + */ + public static AuthoredDraftPublishSelectionBinding capture( + PublishIntent intent, TargetProof target, DraftCommitBinding binding, VisibilityFence fence) { + return new AuthoredDraftPublishSelectionBinding(intent, target, binding, fence); + } + + /** Reconstructs a retained selection and rejects malformed or noncanonical stored bytes. */ + public static AuthoredDraftPublishSelectionBinding fromStored( + String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + if (root == null || !root.isObject() || !"1".equals(requiredText(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported authored Draft selection schema"); + } + JsonNode intentNode = requiredObject(root, "intent"); + PublishIntent intent = + new PublishIntent( + UUID.fromString(requiredText(intentNode, "canonicalTenantId")), + UUID.fromString(requiredText(intentNode, "canonicalVersionId")), + requiredText(intentNode, "publishRequestId"), + requiredText(intentNode, "expectedVersionStateEpoch"), + requiredText(intentNode, "notes"), + UUID.fromString(requiredText(intentNode, "selectedCommitRequestId")), + UUID.fromString(requiredText(intentNode, "selectedCommitId")), + requiredText(intentNode, "selectedCommitDigest")); + JsonNode targetNode = requiredObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(targetNode, "canonicalTenantId")), + UUID.fromString(requiredText(targetNode, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + DraftCommitBinding selectedCommit = + DraftCommitBinding.fromStored( + requiredText(root, "selectedCommitBindingJson"), + requiredText(root, "selectedCommitDigest")); + JsonNode fenceNode = requiredObject(root, "synchronizedFence"); + String fenceResultVectorJson = requiredText(fenceNode, "resultVectorJson"); + requireCanonicalArray(fenceResultVectorJson); + VisibilityFence fence = + new VisibilityFence( + target, + UUID.fromString(requiredText(fenceNode, "requestId")), + UUID.fromString(requiredText(fenceNode, "commitId")), + requiredText(fenceNode, "inputDigest"), + fenceResultVectorJson, + OffsetDateTime.parse(requiredText(fenceNode, "createdAt"))); + AuthoredDraftPublishSelectionBinding selection = + new AuthoredDraftPublishSelectionBinding(intent, target, selectedCommit, fence); + if (!selection.canonicalJson.equals(storedJson) + || !selection.digest.equals(storedDigest) + || !Arrays.equals( + selection.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored authored Draft publication selection is not exact canonical JSON"); + } + return selection; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored authored Draft selection is corrupt", exception); + } + } + + public PublishIntent intent() { + return intent; + } + + public TargetProof target() { + return target; + } + + public DraftCommitBinding selectedCommit() { + return selectedCommit; + } + + public UUID fenceRequestId() { + return fenceRequestId; + } + + public UUID fenceCommitId() { + return fenceCommitId; + } + + public String fenceInputDigest() { + return fenceInputDigest; + } + + public String fenceResultVectorJson() { + return fenceResultVectorJson; + } + + public String fenceCreatedAt() { + return fenceCreatedAt; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelectionBinding selection + && digest.equals(selection.digest) + && Arrays.equals(canonicalBytes, selection.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", "1"); + root.put("intent", intentJson(intent)); + root.put("target", targetJson(target)); + root.put("selectedCommitBindingJson", selectedCommit.canonicalJson()); + root.put("selectedCommitDigest", selectedCommit.digest()); + Map fence = new LinkedHashMap<>(); + fence.put("requestId", fenceRequestId.toString()); + fence.put("commitId", fenceCommitId.toString()); + fence.put("inputDigest", fenceInputDigest); + fence.put("resultVectorJson", fenceResultVectorJson); + fence.put("createdAt", fenceCreatedAt); + root.put("synchronizedFence", fence); + return root; + } + + private static Map intentJson(PublishIntent intent) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", intent.canonicalTenantId().toString()); + object.put("canonicalVersionId", intent.canonicalVersionId().toString()); + object.put("publishRequestId", intent.publishRequestId()); + object.put("expectedVersionStateEpoch", intent.expectedVersionStateEpoch()); + object.put("notes", intent.notes()); + object.put("selectedCommitRequestId", intent.selectedCommitRequestId().toString()); + object.put("selectedCommitId", intent.selectedCommitId().toString()); + object.put("selectedCommitDigest", intent.selectedCommitDigest()); + return object; + } + + private static Map targetJson(TargetProof target) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + object.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + object.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + object.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + object.put("sourceGameTenantKey", target.sourceGameTenantKey()); + object.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return object; + } + + private static JsonNode requiredObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing object field " + field); + } + return value; + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing text field " + field); + } + return value.textValue(); + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireCanonicalArray(String storedJson) { + try { + JsonNode node = JSON.readTree(storedJson); + if (node == null || !node.isArray()) { + throw new IllegalArgumentException("Stored owner result vector is not an array"); + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(storedJson); + if (!Arrays.equals(canonical, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Stored owner result vector is not canonical JSON"); + } + } catch (IOException exception) { + throw new IllegalArgumentException("Stored owner result vector is malformed JSON", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Full caller-supplied intent for selecting one exact Draft commit to publish. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + PublicationDigestRequestBinding.validatePublicationIdentity( + canonicalTenantId.toString(), publishRequestId); + requirePositiveCounter(expectedVersionStateEpoch, "expectedVersionStateEpoch"); + Objects.requireNonNull(notes, "notes"); + requireNonNil(selectedCommitRequestId, "selectedCommitRequestId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireDigest(selectedCommitDigest, "selectedCommitDigest"); + } + } + + private static void requirePositiveCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal string"); + } + } + + private static void requireDigest(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + /** + * Exact previously captured synchronized fence; its structure does not authenticate its owner. + */ + public record VisibilityFence( + TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) {} + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java new file mode 100644 index 0000000000..0d664c9a04 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Original closed publication input; byte integrity never authenticates its producer. */ +public record GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = "game-design-publication-operation/v1"; + + public GameDesignPublicationOperationBinding { + account = + AccountPublicationAuthorizationBinding.fromStored( + Objects.requireNonNull(account).canonicalBytes()); + world = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(world).canonicalBytes()); + var selection = account.input().selection(); + var intent = selection.intent(); + var freeze = world.request(); + if (!account.tenantId().equals(freeze.canonicalTenantId()) + || !intent.canonicalVersionId().equals(freeze.canonicalVersionId()) + || !intent.publishRequestId().equals(freeze.publicationRequestId()) + || !selection.digest().equals("sha256:" + freeze.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(freeze.versionStateEpoch())) + || !intent.selectedCommitId().toString().equals(freeze.appliedCommitId()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()) + .normalizedInput())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + if (!PublicationDigestRequestBinding.full( + account.tenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity() + .equals(freeze.publishWorkflowId())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_WORKFLOW_CONFLICT"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); + return out.toByteArray(); + } + + public static GameDesignPublicationOperationBinding fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var operation = + new GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), + WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication operation"); + } + return operation; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java new file mode 100644 index 0000000000..0acc2b83d4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidence.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; + +/** One authored policy and its original immutable source identity within an owner-sealed set. */ +public record PublishedRealmEntryPolicyEvidence( + UUID policyId, + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy, + String policyDigest) { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PublishedRealmEntryPolicyEvidence { + requireNonNil(policyId, "policyId"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + if (logicalRevisionId == null + || logicalRevisionId.isBlank() + || logicalRevisionId.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(logicalRevisionId)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + policy = requireCanonicalPolicy(policy); + requireDigest(policyDigest, "policyDigest"); + } + + /** Computes the exact Game Design owner policy digest over the actual sealed release identity. */ + public static String calculateDigest( + UUID policyId, + TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) { + requireNonNil(policyId, "policyId"); + Objects.requireNonNull(target, "target"); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Positive published version number required"); + } + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(publishedReleaseBundleDigest, "publishedReleaseBundleDigest"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireDigest(manifestHash, "manifestHash"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + if (logicalRevisionId == null + || logicalRevisionId.isBlank() + || logicalRevisionId.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(logicalRevisionId)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + RealmEntryPolicy exactPolicy = requireCanonicalPolicy(policy); + + Map preimage = new LinkedHashMap<>(); + preimage.put("schema", PublishedRealmEntryPolicySetEvidence.POLICY_DIGEST_SCHEMA); + preimage.put("policyId", policyId.toString()); + preimage.put("target", PublishedRealmEntryPolicySetEvidence.targetProofObject(target)); + preimage.put("versionNumber", versionNumber); + preimage.put("sourceCommitId", sourceCommitId.toString()); + preimage.put("sourceRevisionId", sourceRevisionId.toString()); + preimage.put("logicalRevisionId", logicalRevisionId); + preimage.put("publishedReleaseBundleRef", publishedReleaseBundleRef); + preimage.put("publishedReleaseBundleDigest", publishedReleaseBundleDigest); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + try { + preimage.put("policy", JSON.readTree(exactPolicy.canonicalJson())); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Canonical realm-entry policy JSON is invalid", invalid); + } + return sha256(canonicalize(preimage)); + } + + /** Verifies this row against the shared sealed publication context. */ + public boolean hasValidDigest(PublishedRealmEntryPolicySetEvidence set) { + if (set == null) return false; + try { + return policyDigest.equals( + calculateDigest( + policyId, + set.target(), + set.versionNumber(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + sourceCommitId, + sourceRevisionId, + logicalRevisionId, + policy)); + } catch (IllegalArgumentException invalid) { + return false; + } + } + + /** Requires exact digest agreement with the shared sealed publication context. */ + public PublishedRealmEntryPolicyEvidence requireValidDigest( + PublishedRealmEntryPolicySetEvidence set) { + if (!hasValidDigest(set)) { + throw new IllegalArgumentException( + "Published realm-entry policy digest differs from evidence"); + } + return this; + } + + static RealmEntryPolicy requireCanonicalPolicy(RealmEntryPolicy policy) { + Objects.requireNonNull(policy, "policy"); + RealmEntryPolicy parsed = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), JSON); + if (!parsed.equals(policy)) { + throw new IllegalArgumentException("Policy fields contradict canonical policy JSON"); + } + return parsed; + } + + static byte[] canonicalize(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalArgumentException("Policy evidence could not be canonicalized", invalid); + } + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + static void requireText(String value, String name) { + if (value == null || value.isBlank() || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Canonical nonblank " + name + " required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException("Valid UTF-8 " + name + " required"); + } + } + + static void requireDigest(String value, String name) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical SHA-256 " + name + " required"); + } + } + + static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java new file mode 100644 index 0000000000..0b34e8d1eb --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; + +/** Closed wire mapping for exact, complete published realm-entry policy owner reads. */ +public final class PublishedRealmEntryPolicyReadGrpcCodec { + private static final int SCHEMA_VERSION = 1; + + private PublishedRealmEntryPolicyReadGrpcCodec() {} + + public record ResolveRequest( + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + String realmSlug) { + public ResolveRequest { + requireNamespace(targetNamespace); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + } + } + + public record ListRequest( + String targetNamespace, UUID readRequestId, UUID canonicalTenantId, UUID canonicalVersionId) { + public ListRequest { + requireNamespace(targetNamespace); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + } + } + + public static ResolvePublishedRealmEntryPolicyRequest toRequest(ResolveRequest request) { + Objects.requireNonNull(request, "request"); + return ResolvePublishedRealmEntryPolicyRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmSlug(request.realmSlug()) + .build(); + } + + public static ResolveRequest fromRequest(ResolvePublishedRealmEntryPolicyRequest wire) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 realm policy resolve request required"); + } + return new ResolveRequest( + wire.getTargetNamespace(), + canonicalUuid(wire.getReadRequestId(), "readRequestId"), + canonicalUuid(wire.getCanonicalTenantId(), "canonicalTenantId"), + canonicalUuid(wire.getCanonicalVersionId(), "canonicalVersionId"), + wire.getWorldSlug(), + wire.getRealmSlug()); + } + + public static ListPublishedRealmEntryPoliciesRequest toRequest(ListRequest request) { + Objects.requireNonNull(request, "request"); + return ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .build(); + } + + public static ListRequest fromRequest(ListPublishedRealmEntryPoliciesRequest wire) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 realm policy list request required"); + } + return new ListRequest( + wire.getTargetNamespace(), + canonicalUuid(wire.getReadRequestId(), "readRequestId"), + canonicalUuid(wire.getCanonicalTenantId(), "canonicalTenantId"), + canonicalUuid(wire.getCanonicalVersionId(), "canonicalVersionId")); + } + + public static ResolvePublishedRealmEntryPolicyResponse toResponse( + ResolveRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + PublishedRealmEntryPolicySetEvidence complete = verifiedFor(request, evidence); + requireSelector(complete, request.worldSlug(), request.realmSlug()); + return ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setRequest(toRequest(request)) + .setPolicySetEvidence(ByteString.copyFrom(complete.canonicalBytes())) + .build(); + } + + public static PublishedRealmEntryPolicySetEvidence fromResponse( + ResolveRequest request, ResolvePublishedRealmEntryPolicyResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete realm policy resolve response required"); + } + ResolveRequest echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("Realm policy resolve response changed the exact request"); + } + PublishedRealmEntryPolicySetEvidence complete = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPolicySetEvidence().toByteArray()); + requireTarget(request.canonicalTenantId(), request.canonicalVersionId(), complete); + requireSelector(complete, request.worldSlug(), request.realmSlug()); + return complete; + } + + public static ListPublishedRealmEntryPoliciesResponse toResponse( + ListRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + PublishedRealmEntryPolicySetEvidence complete = verifiedFor(request, evidence); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(toRequest(request)) + .setPolicySetEvidence(ByteString.copyFrom(complete.canonicalBytes())) + .build(); + } + + public static PublishedRealmEntryPolicySetEvidence fromResponse( + ListRequest request, ListPublishedRealmEntryPoliciesResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete realm policy list response required"); + } + ListRequest echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("Realm policy list response changed the exact request"); + } + PublishedRealmEntryPolicySetEvidence complete = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPolicySetEvidence().toByteArray()); + requireTarget(request.canonicalTenantId(), request.canonicalVersionId(), complete); + return complete; + } + + private static PublishedRealmEntryPolicySetEvidence verifiedFor( + ResolveRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + Objects.requireNonNull(request, "request"); + return verifiedFor(request.canonicalTenantId(), request.canonicalVersionId(), evidence); + } + + private static PublishedRealmEntryPolicySetEvidence verifiedFor( + ListRequest request, PublishedRealmEntryPolicySetEvidence evidence) { + Objects.requireNonNull(request, "request"); + return verifiedFor(request.canonicalTenantId(), request.canonicalVersionId(), evidence); + } + + private static PublishedRealmEntryPolicySetEvidence verifiedFor( + UUID tenantId, UUID versionId, PublishedRealmEntryPolicySetEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + PublishedRealmEntryPolicySetEvidence complete = + PublishedRealmEntryPolicySetEvidence.fromStored(evidence.canonicalBytes()); + requireTarget(tenantId, versionId, complete); + return complete; + } + + private static void requireTarget( + UUID tenantId, UUID versionId, PublishedRealmEntryPolicySetEvidence evidence) { + if (!evidence.target().canonicalTenantId().equals(tenantId) + || !evidence.target().canonicalVersionId().equals(versionId)) { + throw new IllegalArgumentException( + "Published policy evidence changed the exact owner target"); + } + } + + private static void requireSelector( + PublishedRealmEntryPolicySetEvidence evidence, String worldSlug, String realmSlug) { + if (evidence.policies().stream() + .noneMatch( + policy -> + policy.policy().worldSlug().equals(worldSlug) + && policy.policy().realmSlug().equals(realmSlug))) { + throw new IllegalArgumentException( + "Published policy set does not contain the exact selector"); + } + } + + private static UUID canonicalUuid(String value, String name) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, name)); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException("Canonical non-nil " + name + " required"); + } + return parsed; + } catch (RuntimeException invalid) { + if (invalid instanceof IllegalArgumentException argument + && argument.getMessage() != null + && argument.getMessage().startsWith("Canonical non-nil")) { + throw argument; + } + throw new IllegalArgumentException("Canonical non-nil " + name + " required", invalid); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + name + " required"); + } + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical target namespace required"); + } + } + + private static void requireSlug(String slug, String name) { + if (!RealmEntryPolicy.isCanonicalSlug(slug)) { + throw new IllegalArgumentException("Canonical " + name + " required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java new file mode 100644 index 0000000000..2bfa51ccf9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -0,0 +1,816 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Complete immutable policy source and original PUBLISHED terminal evidence; decoding proves + * integrity only. + */ +public record PublishedRealmEntryPolicySetEvidence( + TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + int policyCount, + String policySetDigest, + List policies) { + public static final String POLICY_DIGEST_SCHEMA = "game-design-published-realm-policy/v1"; + public static final String SET_DIGEST_SCHEMA = "game-design-published-realm-policy-set/v1"; + public static final String CARRIER_SCHEMA = "game-design-published-realm-policy-evidence/v1"; + public static final String CAPTURE_SCHEMA = "game-design-realm-policy-source-capture/v1"; + public static final String SNAPSHOT_SCHEMA = "game-design-realm-policy-snapshot/v1"; + public static final int MAX_POLICIES = 128; + + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public PublishedRealmEntryPolicySetEvidence { + Objects.requireNonNull(target, "target"); + PublishedRealmEntryPolicyEvidence.requireNonNil(sourceCommitId, "sourceCommitId"); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Published policy version number must be positive"); + } + if (sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical captured source epoch required"); + } + PublishedRealmEntryPolicyEvidence.requireText( + publishedReleaseBundleRef, "publishedReleaseBundleRef"); + PublishedRealmEntryPolicyEvidence.requireDigest( + publishedReleaseBundleDigest, "publishedReleaseBundleDigest"); + PublishedRealmEntryPolicyEvidence.requireText(publishWorkflowId, "publishWorkflowId"); + PublishedRealmEntryPolicyEvidence.requireDigest(manifestHash, "manifestHash"); + if (publicationVersionStateEpoch <= 0) { + throw new IllegalArgumentException("Original publication epoch must be positive"); + } + operationBytes = nonEmptyCopy(operationBytes, "operationBytes"); + captureBytes = nonEmptyCopy(captureBytes, "captureBytes"); + terminalEvidenceBytes = nonEmptyCopy(terminalEvidenceBytes, "terminalEvidenceBytes"); + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policyCount < 1 || policyCount > MAX_POLICIES || policyCount != policies.size()) { + throw new IllegalArgumentException("Complete bounded policy-set cardinality required"); + } + PublishedRealmEntryPolicyEvidence.requireDigest(policySetDigest, "policySetDigest"); + + validatePublicationContext( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies); + if (!calculatePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest)) { + throw new IllegalArgumentException("Published policy-set digest differs from evidence"); + } + for (PublishedRealmEntryPolicyEvidence policy : policies) { + if (!policy + .policyDigest() + .equals( + PublishedRealmEntryPolicyEvidence.calculateDigest( + policy.policyId(), + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + policy.sourceCommitId(), + policy.sourceRevisionId(), + policy.logicalRevisionId(), + policy.policy()))) { + throw new IllegalArgumentException("Published policy digest differs from evidence"); + } + } + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof PublishedRealmEntryPolicySetEvidence set)) return false; + return versionNumber == set.versionNumber + && publicationVersionStateEpoch == set.publicationVersionStateEpoch + && policyCount == set.policyCount + && target.equals(set.target) + && sourceCommitId.equals(set.sourceCommitId) + && sourceEpoch.equals(set.sourceEpoch) + && publishedReleaseBundleRef.equals(set.publishedReleaseBundleRef) + && publishedReleaseBundleDigest.equals(set.publishedReleaseBundleDigest) + && publishWorkflowId.equals(set.publishWorkflowId) + && manifestHash.equals(set.manifestHash) + && policySetDigest.equals(set.policySetDigest) + && Arrays.equals(operationBytes, set.operationBytes) + && Arrays.equals(captureBytes, set.captureBytes) + && Arrays.equals(terminalEvidenceBytes, set.terminalEvidenceBytes) + && policies.equals(set.policies); + } + + @Override + public int hashCode() { + int hash = + Objects.hash( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + policyCount, + policySetDigest, + policies); + hash = 31 * hash + Arrays.hashCode(operationBytes); + hash = 31 * hash + Arrays.hashCode(captureBytes); + return 31 * hash + Arrays.hashCode(terminalEvidenceBytes); + } + + /** Exact RFC 8785 JSON representation used for canonical shared storage or handoff. */ + public String canonicalJson() { + return new String(canonicalBytes(), StandardCharsets.UTF_8); + } + + /** Returns a defensive copy of the exact canonical carrier bytes. */ + public byte[] canonicalBytes() { + return canonicalize(toJsonObject()); + } + + /** Strictly decodes the complete owner evidence and rejects unknown or noncanonical bytes. */ + public static PublishedRealmEntryPolicySetEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = strictUtf8(stored); + if (!Arrays.equals(stored, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw new IllegalArgumentException("Stored policy evidence is not RFC 8785 canonical JSON"); + } + JsonNode root = JSON.readTree(json); + requireFields( + root, + "schema", + "target", + "versionNumber", + "sourceCommitId", + "sourceEpoch", + "publishedReleaseBundleRef", + "publishedReleaseBundleDigest", + "publishWorkflowId", + "manifestHash", + "publicationVersionStateEpoch", + "operationBytesBase64", + "captureBytesBase64", + "terminalEvidenceBytesBase64", + "policyCount", + "policySetDigest", + "policies"); + if (!CARRIER_SCHEMA.equals(requiredText(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published policy evidence schema"); + } + TargetProof target = parseTarget(requiredObject(root, "target")); + int versionNumber = positiveInt(root, "versionNumber"); + UUID sourceCommitId = canonicalUuid(requiredText(root, "sourceCommitId")); + String sourceEpoch = requiredText(root, "sourceEpoch"); + String releaseRef = requiredText(root, "publishedReleaseBundleRef"); + String releaseDigest = requiredText(root, "publishedReleaseBundleDigest"); + String workflowId = requiredText(root, "publishWorkflowId"); + String manifestHash = requiredText(root, "manifestHash"); + long publicationEpoch = positiveLongString(root, "publicationVersionStateEpoch"); + byte[] operationBytes = requiredBase64(root, "operationBytesBase64"); + byte[] captureBytes = requiredBase64(root, "captureBytesBase64"); + byte[] terminalBytes = requiredBase64(root, "terminalEvidenceBytesBase64"); + int policyCount = positiveInt(root, "policyCount"); + String setDigest = requiredText(root, "policySetDigest"); + JsonNode policyNodes = requiredArray(root, "policies"); + List policies = new ArrayList<>(policyNodes.size()); + for (JsonNode node : policyNodes) { + requireFields( + node, + "policyId", + "sourceCommitId", + "sourceRevisionId", + "logicalRevisionId", + "policy", + "policyDigest"); + String policyJson = canonicalJson(node.get("policy")); + policies.add( + new PublishedRealmEntryPolicyEvidence( + canonicalUuid(requiredText(node, "policyId")), + canonicalUuid(requiredText(node, "sourceCommitId")), + canonicalUuid(requiredText(node, "sourceRevisionId")), + requiredText(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(policyJson, JSON), + requiredText(node, "policyDigest"))); + } + var result = + new PublishedRealmEntryPolicySetEvidence( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + releaseRef, + releaseDigest, + workflowId, + manifestHash, + publicationEpoch, + operationBytes, + captureBytes, + terminalBytes, + policyCount, + setDigest, + policies); + if (!Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Stored published policy evidence changed on readback"); + } + return result; + } catch (IOException | RuntimeException invalid) { + if (invalid instanceof IllegalArgumentException argument) throw argument; + throw new IllegalArgumentException("Stored published policy evidence is invalid", invalid); + } + } + + /** Verifies the set and all child digests against the retained immutable evidence. */ + public boolean hasValidDigest() { + try { + return calculatePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest) + && policies.stream().allMatch(policy -> policy.hasValidDigest(this)); + } catch (IllegalArgumentException invalid) { + return false; + } + } + + public PublishedRealmEntryPolicySetEvidence requireValidDigest() { + if (!hasValidDigest()) { + throw new IllegalArgumentException( + "Published realm-entry policy-set digest differs from evidence"); + } + return this; + } + + /** Exact current Game Design policy digest preimage and RFC 8785/SHA-256 encoding. */ + public static String policyDigest( + UUID policyId, + TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) { + return PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + sourceCommitId, + sourceRevisionId, + logicalRevisionId, + policy); + } + + /** Exact current Game Design complete-set digest preimage and RFC 8785/SHA-256 encoding. */ + public static String calculatePolicySetDigest( + TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + Objects.requireNonNull(policies, "policies"); + List exactPolicies = List.copyOf(policies); + requirePolicySetSemantics(exactPolicies); + List orderedPolicies = + exactPolicies.stream() + .sorted( + java.util.Comparator.comparing( + (PublishedRealmEntryPolicyEvidence policy) -> policy.policy().worldSlug()) + .thenComparing(policy -> policy.policy().realmSlug())) + .toList(); + List> orderedEvidence = + orderedPolicies.stream() + .map( + policy -> { + Map row = new LinkedHashMap<>(); + row.put("policyId", policy.policyId().toString()); + row.put("sourceCommitId", policy.sourceCommitId().toString()); + row.put("sourceRevisionId", policy.sourceRevisionId().toString()); + row.put("logicalRevisionId", policy.logicalRevisionId()); + row.put("worldSlug", policy.policy().worldSlug()); + row.put("realmSlug", policy.policy().realmSlug()); + row.put("policyDigest", policy.policyDigest()); + return row; + }) + .toList(); + Map preimage = new LinkedHashMap<>(); + preimage.put("schema", SET_DIGEST_SCHEMA); + preimage.put("target", targetProofObject(target)); + preimage.put("versionNumber", versionNumber); + preimage.put("sourceCommitId", sourceCommitId.toString()); + preimage.put("sourceEpoch", sourceEpoch); + preimage.put("publishedReleaseBundleRef", publishedReleaseBundleRef); + preimage.put("publishedReleaseBundleDigest", publishedReleaseBundleDigest); + preimage.put("publishWorkflowId", publishWorkflowId); + preimage.put("manifestHash", manifestHash); + preimage.put("publicationVersionStateEpoch", Long.toString(publicationVersionStateEpoch)); + preimage.put("operationDigest", digestBytes(operationBytes)); + preimage.put("captureDigest", digestBytes(captureBytes)); + preimage.put("terminalEvidenceDigest", digestBytes(terminalEvidenceBytes)); + preimage.put("policyCount", orderedEvidence.size()); + preimage.put("policies", orderedEvidence); + return PublishedRealmEntryPolicyEvidence.sha256(canonicalize(preimage)); + } + + /** Exact shared TargetProof representation used by both local owner digest preimages. */ + public static String targetProofJson(TargetProof target) { + return new String(canonicalize(targetProofObject(target)), StandardCharsets.UTF_8); + } + + static Map targetProofObject(TargetProof target) { + Objects.requireNonNull(target, "target"); + Map value = new LinkedHashMap<>(); + value.put("canonicalTenantId", target.canonicalTenantId().toString()); + value.put("canonicalVersionId", target.canonicalVersionId().toString()); + value.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + value.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + value.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + value.put("sourceGameTenantKey", target.sourceGameTenantKey()); + value.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return value; + } + + private static void validatePublicationContext( + TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + var selection = operation.account().input().selection(); + if (!selection.target().equals(target) + || !selection.selectedCommit().commitId().equals(sourceCommitId) + || !operation.world().request().publishWorkflowId().equals(publishWorkflowId)) { + throw new IllegalArgumentException( + "Publication operation differs from exact TargetProof or source"); + } + + CapturedSource captured = parseCapture(captureBytes, operationBytes); + if (!captured.target().equals(target) + || !captured.binding().equals(selection.selectedCommit()) + || !captured.binding().commitId().equals(sourceCommitId) + || !captured.sourceEpoch().equals(sourceEpoch) + || !captured.policies().equals(policies.stream().map(PolicySource::from).toList())) { + throw new IllegalArgumentException( + "Captured source differs from selected synchronized policy set"); + } + + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operationBytes)) { + throw new IllegalArgumentException( + "Original PUBLISHED terminal differs from operation bytes"); + } + var release = terminal.releaseContent(); + if (!release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || release.versionNumber() != versionNumber + || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !release.contentDigest().equals(publishedReleaseBundleDigest) + || !release.publishWorkflowId().equals(publishWorkflowId) + || !release.manifestHash().equals(manifestHash) + || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { + throw new IllegalArgumentException("Actual sealed release identity differs from policy set"); + } + requireCanonicalPolicyOrder(policies); + } + + private static CapturedSource parseCapture(byte[] bytes, byte[] expectedOperationBytes) { + FrameReader capture = new FrameReader(bytes); + capture.expect(CAPTURE_SCHEMA); + byte[] operationBytes = capture.bytes(); + byte[] snapshotBytes = capture.bytes(); + capture.requireEnd(); + if (!Arrays.equals(operationBytes, expectedOperationBytes) + || !Arrays.equals( + operationBytes, + GameDesignPublicationOperationBinding.fromStored(operationBytes).canonicalBytes())) { + throw new IllegalArgumentException("Captured source operation bytes changed"); + } + String snapshotJson = strictUtf8(snapshotBytes); + try { + if (!Arrays.equals(snapshotBytes, Rfc8785CanonicalJson.canonicalizeUtf8(snapshotJson))) { + throw new IllegalArgumentException("Captured policy snapshot is not canonical JSON"); + } + JsonNode snapshot = JSON.readTree(snapshotJson); + requireFields(snapshot, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); + if (!SNAPSHOT_SCHEMA.equals(requiredText(snapshot, "schema"))) { + throw new IllegalArgumentException("Unsupported captured policy snapshot schema"); + } + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + requiredText(snapshot, "bindingJson"), requiredText(snapshot, "bindingDigest")); + String sourceEpoch = requiredText(snapshot, "sourceEpoch"); + JsonNode policyNodes = requiredArray(snapshot, "policies"); + if (policyNodes.size() == 0 || policyNodes.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete nonempty captured policy source required"); + } + List policies = new ArrayList<>(policyNodes.size()); + for (JsonNode node : policyNodes) { + requireFields(node, "commitId", "revisionId", "logicalRevisionId", "policy"); + policies.add( + new PolicySource( + canonicalUuid(requiredText(node, "commitId")), + canonicalUuid(requiredText(node, "revisionId")), + requiredText(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(canonicalJson(node.get("policy")), JSON))); + } + validatePolicySources(policies); + return new CapturedSource(binding.target(), binding, sourceEpoch, List.copyOf(policies)); + } catch (IOException | RuntimeException invalid) { + if (invalid instanceof IllegalArgumentException argument) throw argument; + throw new IllegalArgumentException("Captured policy source is invalid", invalid); + } + } + + private static void requireCanonicalPolicyOrder( + List policies) { + requirePolicySetSemantics(policies); + String previousWorld = null; + String previousRealm = null; + for (PublishedRealmEntryPolicyEvidence evidence : policies) { + String world = evidence.policy().worldSlug(); + String realm = evidence.policy().realmSlug(); + if (previousWorld != null + && (previousWorld.compareTo(world) > 0 + || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { + throw new IllegalArgumentException("Published policy selector order is not canonical"); + } + previousWorld = world; + previousRealm = realm; + } + } + + private static void requirePolicySetSemantics(List policies) { + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete policy set must contain 1 through 128 rows"); + } + var realmSlugs = new HashSet(); + var revisions = new HashSet(); + var policyIds = new HashSet(); + int visiblePublicProduction = 0; + for (PublishedRealmEntryPolicyEvidence evidence : policies) { + Objects.requireNonNull(evidence, "policy evidence"); + if (!realmSlugs.add(evidence.policy().realmSlug())) { + throw new IllegalArgumentException("Tenant-wide realm selector is duplicated"); + } + if (!revisions.add(evidence.sourceRevisionId())) { + throw new IllegalArgumentException("Authored policy revision is duplicated"); + } + if (!policyIds.add(evidence.policyId())) { + throw new IllegalArgumentException("Allocated policy identity is duplicated"); + } + if (evidence.policy().visible() && evidence.policy().publicProduction()) { + visiblePublicProduction++; + } + } + if (visiblePublicProduction != 1) { + throw new IllegalArgumentException("Exactly one visible public-production realm is required"); + } + } + + private static void validatePolicySources(List policies) { + var realms = new HashSet(); + var revisions = new HashSet(); + String previousWorld = null; + String previousRealm = null; + for (PolicySource policy : policies) { + if (!realms.add(policy.policy().realmSlug()) || !revisions.add(policy.sourceRevisionId())) { + throw new IllegalArgumentException("Captured source repeats a selector or revision"); + } + String world = policy.policy().worldSlug(); + String realm = policy.policy().realmSlug(); + if (previousWorld != null + && (previousWorld.compareTo(world) > 0 + || (previousWorld.equals(world) && previousRealm.compareTo(realm) >= 0))) { + throw new IllegalArgumentException("Captured source policy order is not canonical"); + } + previousWorld = world; + previousRealm = realm; + } + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schema", CARRIER_SCHEMA); + root.put("target", targetProofObject(target)); + root.put("versionNumber", versionNumber); + root.put("sourceCommitId", sourceCommitId.toString()); + root.put("sourceEpoch", sourceEpoch); + root.put("publishedReleaseBundleRef", publishedReleaseBundleRef); + root.put("publishedReleaseBundleDigest", publishedReleaseBundleDigest); + root.put("publishWorkflowId", publishWorkflowId); + root.put("manifestHash", manifestHash); + root.put("publicationVersionStateEpoch", Long.toString(publicationVersionStateEpoch)); + root.put("operationBytesBase64", Base64.getEncoder().encodeToString(operationBytes)); + root.put("captureBytesBase64", Base64.getEncoder().encodeToString(captureBytes)); + root.put( + "terminalEvidenceBytesBase64", Base64.getEncoder().encodeToString(terminalEvidenceBytes)); + root.put("policyCount", policyCount); + root.put("policySetDigest", policySetDigest); + root.put( + "policies", + policies.stream() + .map( + evidence -> { + Map row = new LinkedHashMap<>(); + row.put("policyId", evidence.policyId().toString()); + row.put("sourceCommitId", evidence.sourceCommitId().toString()); + row.put("sourceRevisionId", evidence.sourceRevisionId().toString()); + row.put("logicalRevisionId", evidence.logicalRevisionId()); + try { + row.put("policy", JSON.readTree(evidence.policy().canonicalJson())); + } catch (RuntimeException impossible) { + throw new IllegalStateException( + "Canonical realm policy became invalid", impossible); + } + row.put("policyDigest", evidence.policyDigest()); + return row; + }) + .toList()); + return root; + } + + private static byte[] nonEmptyCopy(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Nonempty " + name + " required"); + } + return value.clone(); + } + + private static String digestBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Nonempty immutable source bytes required for digest"); + } + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static byte[] canonicalize(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalArgumentException( + "Published policy evidence could not be canonicalized", invalid); + } + } + + private static String canonicalJson(JsonNode node) { + if (node == null) throw new IllegalArgumentException("Policy JSON object is required"); + return new String(canonicalize(node), StandardCharsets.UTF_8); + } + + private static TargetProof parseTarget(JsonNode node) { + requireFields( + node, + "canonicalTenantId", + "canonicalVersionId", + "gameDesignVersionRowId", + "gameDesignVersionTenantKey", + "sourceGameRowId", + "sourceGameTenantKey", + "sourceProvenanceKind"); + return new TargetProof( + canonicalUuid(requiredText(node, "canonicalTenantId")), + canonicalUuid(requiredText(node, "canonicalVersionId")), + positiveLongString(node, "gameDesignVersionRowId"), + requiredText(node, "gameDesignVersionTenantKey"), + positiveLongString(node, "sourceGameRowId"), + requiredText(node, "sourceGameTenantKey"), + requiredText(node, "sourceProvenanceKind")); + } + + private static UUID canonicalUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("UUID text is not canonical"); + } + return parsed; + } + + private static String requiredText(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Text value required: " + name); + } + return value.asText(); + } + + private static int positiveInt(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToInt() + || value.intValue() <= 0) { + throw new IllegalArgumentException("Positive integer required: " + name); + } + return value.intValue(); + } + + private static long positiveLongString(JsonNode node, String name) { + String value = requiredText(node, name); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical positive decimal string required: " + name); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Counter out of range: " + name, invalid); + } + } + + private static byte[] requiredBase64(JsonNode node, String name) { + String value = requiredText(node, name); + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(decoded).equals(value)) { + throw new IllegalArgumentException("Noncanonical Base64 value: " + name); + } + return decoded; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid Base64 value: " + name, invalid); + } + } + + private static JsonNode requiredObject(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException("Object value required: " + name); + } + return value; + } + + private static JsonNode requiredArray(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException("Array value required: " + name); + } + return value; + } + + private static void requireFields(JsonNode node, String... expected) { + if (node == null || !node.isObject() || node.size() != expected.length) { + throw new IllegalArgumentException("Closed canonical evidence fields required"); + } + for (String name : expected) { + if (!node.has(name)) { + throw new IllegalArgumentException("Missing canonical evidence field: " + name); + } + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException invalid) { + throw new IllegalArgumentException("Evidence bytes are not valid UTF-8", invalid); + } + } + + private record PolicySource( + UUID sourceCommitId, + UUID sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) { + private static PolicySource from(PublishedRealmEntryPolicyEvidence policy) { + return new PolicySource( + policy.sourceCommitId(), + policy.sourceRevisionId(), + policy.logicalRevisionId(), + policy.policy()); + } + } + + private record CapturedSource( + TargetProof target, + DraftCommitBinding binding, + String sourceEpoch, + List policies) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java new file mode 100644 index 0000000000..75ccc90dc2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed v1 authored realm-entry policy shared by the publication owner and runtime receivers. */ +public record RealmEntryPolicy( + int schemaVersion, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + StateScope stateScope, + EntryPolicy entryPolicy, + String canonicalJson) { + public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_JSON_BYTES = 4096; + public static final int MAX_SLUG_LENGTH = 64; + public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; + + private static final Set FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + + public enum StateScope { + SHARED, + ISOLATED + } + + public enum EntryPolicy { + PRESEEDED_ONLY + } + + /** Parses valid v1 JSON and returns the RFC 8785 canonical policy representation. */ + public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { + if (json == null || json.isBlank()) { + throw invalid("data is required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(json)) { + throw invalid("data must be valid UTF-8"); + } + ByteBuffer inputBytes = StandardCharsets.UTF_8.encode(json); + if (inputBytes.remaining() > MAX_JSON_BYTES) { + throw invalid("data exceeds the v1 byte limit"); + } + + JsonNode root; + String canonicalJson; + try { + canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + root = objectMapper.readTree(canonicalJson); + } catch (IOException | RuntimeException exception) { + throw invalid("data must be valid unambiguous JSON"); + } + if (root == null || !root.isObject()) { + throw invalid("must be a JSON object"); + } + for (String field : FIELDS) { + if (!root.has(field)) { + throw invalid(field + " is required"); + } + } + if (root.size() != FIELDS.size()) { + throw invalid("must contain exactly the v1 fields"); + } + + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != SCHEMA_VERSION) { + throw invalid("schemaVersion must be the integer 1"); + } + String worldSlug = requireSlug(root, "worldSlug"); + String worldDisplayName = requireDisplayName(root, "worldDisplayName"); + String realmSlug = requireSlug(root, "realmSlug"); + String realmDisplayName = requireDisplayName(root, "realmDisplayName"); + boolean visible = requireBoolean(root, "visible"); + boolean publicProduction = requireBoolean(root, "publicProduction"); + StateScope stateScope = requireEnum(root, "stateScope", StateScope.class); + EntryPolicy entryPolicy = requireEnum(root, "entryPolicy", EntryPolicy.class); + + return new RealmEntryPolicy( + SCHEMA_VERSION, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + entryPolicy, + canonicalJson); + } + + /** Parses policy evidence that is required to already use its exact canonical JSON spelling. */ + public static RealmEntryPolicy parseCanonical(String json, ObjectMapper objectMapper) { + RealmEntryPolicy policy = parse(json, objectMapper); + if (!json.equals(policy.canonicalJson())) { + throw invalid("published policy JSON is not canonical"); + } + return policy; + } + + public static boolean isCanonicalSlug(String value) { + return value != null + && value.length() <= MAX_SLUG_LENGTH + && SLUG_PATTERN.matcher(value).matches(); + } + + private static String requireSlug(JsonNode root, String field) { + String value = requireText(root, field); + if (!isCanonicalSlug(value)) { + throw invalid(field + " must be a canonical lower-case slug"); + } + return value; + } + + private static String requireDisplayName(JsonNode root, String field) { + String value = requireText(root, field); + if (!value.equals(value.strip()) + || value.codePointCount(0, value.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || value.codePoints().anyMatch(Character::isISOControl)) { + throw invalid(field + " is outside the v1 text bounds"); + } + return value; + } + + private static String requireText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw invalid(field + " must be a nonblank string"); + } + return value.asText(); + } + + private static boolean requireBoolean(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isBoolean()) { + throw invalid(field + " must be an explicit boolean"); + } + return value.booleanValue(); + } + + private static > T requireEnum(JsonNode root, String field, Class type) { + String value = requireText(root, field); + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException exception) { + throw invalid("unsupported " + field); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: realmEntryPolicy " + message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java new file mode 100644 index 0000000000..a6a4a31297 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Canonical request and receipt digests for Game Design authored-world source evidence. */ +public final class AuthoredWorldSourceDigest { + private static final String REQUEST_DOMAIN = "game-design-authored-world-source-request/v1"; + private static final String RECEIPT_DOMAIN = "game-design-authored-world-source-receipt/v1"; + private static final Pattern CANONICAL_SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldSourceDigest() {} + + public static String requestDigest( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return GameTenantCreationDigest.digest( + REQUEST_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName); + } + + public static String evidenceDigest( + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + requireNonNil(operationId, "operationId"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + validateSourceGameTenantKey(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { + throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); + } + return GameTenantCreationDigest.digest( + RECEIPT_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + operationId.toString(), + requestDigest, + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind); + } + + public static void validateReadSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(worldSlug, "worldSlug"); + } + + private static void validateRequestTuple( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(registrationRequestId, "registrationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(tenantSlug, "tenantSlug"); + validateSlug(worldSlug, "worldSlug"); + validateDisplayName(worldDisplayName); + } + + private static void validateSlug(String value, String label) { + Objects.requireNonNull(value, label); + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + if (byteLength == 0 || byteLength > 120 || !CANONICAL_SLUG.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical routing selector"); + } + } + + private static void validateDisplayName(String value) { + Objects.requireNonNull(value, "worldDisplayName"); + if (value.isBlank() || value.length() > 200 || value.codePointCount(0, value.length()) > 100) { + throw new IllegalArgumentException( + "worldDisplayName must be nonblank and contain at most 100 Unicode code points"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void validateSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java new file mode 100644 index 0000000000..c09fb7a277 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** Closed immutable Game Design evidence for one registered authored-world selector source. */ +public record AuthoredWorldSourceEvidence( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + + public AuthoredWorldSourceEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world source schema version"); + } + Objects.requireNonNull(requestDigest, "requestDigest"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + String expectedRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + if (!expectedRequestDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the registration tuple"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + if (!GameTenantCreationDigest.isDigest(evidenceDigest)) { + throw new IllegalArgumentException("evidenceDigest must be a lowercase SHA-256 digest"); + } + String expectedEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + if (!expectedEvidenceDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Evidence digest does not match the immutable tuple"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java new file mode 100644 index 0000000000..06366df88b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.common.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable Game Design owner evidence for one persisted runtime tenant identity. */ +public record RuntimeTenantIdentityEvidence( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_SOURCE_KEY_CODE_POINTS = 36; + private static final int MAX_SOURCE_KEY_UTF16_LENGTH = 72; + + public RuntimeTenantIdentityEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported runtime tenant identity schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); + if (sourceGameTenantKey.isBlank() + || sourceGameTenantKey.length() > MAX_SOURCE_KEY_UTF16_LENGTH + || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) + > MAX_SOURCE_KEY_CODE_POINTS + || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey)) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { + throw new IllegalArgumentException("Runtime tenant provenance kind is not recognized"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java new file mode 100644 index 0000000000..86a1e642c9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.world; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Read-only Entity-facing source evidence for one exact current public-production roster target. + * The account UUID is request correlation only; this evidence does not establish Account authority, + * actor ownership, or gameplay admission. + */ +public record CanonicalGameplayRosterOwnerReadEvidence( + Request request, + String admissionPointerSnapshotDigest, + GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof, + PublishedRealmEntryPolicySetEvidence publishedPolicySetEvidence) { + public static final int MAX_OWNER_PROOF_BYTES = 16 * 1024; + public static final int MAX_POLICY_SET_BYTES = 2 * 1024 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POINTER_SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + public CanonicalGameplayRosterOwnerReadEvidence { + Objects.requireNonNull(request, "request"); + if (admissionPointerSnapshotDigest == null + || !POINTER_SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Admission pointer snapshot digest must be raw lowercase 64-character SHA-256 hex"); + } + Objects.requireNonNull(gameSessionOwnerProof, "gameSessionOwnerProof"); + Objects.requireNonNull(publishedPolicySetEvidence, "publishedPolicySetEvidence"); + + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(gameSessionOwnerProof); + byte[] policyBytes = publishedPolicySetEvidence.canonicalBytes(); + if (proofBytes.length > MAX_OWNER_PROOF_BYTES || policyBytes.length > MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Canonical roster owner evidence exceeds its size bound"); + } + gameSessionOwnerProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(proofBytes); + publishedPolicySetEvidence = PublishedRealmEntryPolicySetEvidence.fromStored(policyBytes); + requireProofMatches(request, gameSessionOwnerProof); + requirePolicyMatches(request, publishedPolicySetEvidence); + } + + public PublishedRealmEntryPolicyEvidence selectedPolicyEvidence() { + return publishedPolicySetEvidence.policies().stream() + .filter( + evidence -> + evidence.policy().worldSlug().equals(request.worldSlug()) + && evidence.policy().realmSlug().equals(request.realmSlug())) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Exact published policy is unavailable")); + } + + private static void requireProofMatches( + Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { + var hold = proof.holdIdentity().request(); + if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + || !hold.targetNamespace().equals(request.targetNamespace()) + || !hold.canonicalTenantId().equals(request.canonicalTenantUuid()) + || !hold.worldSlug().equals(request.worldSlug()) + || !hold.realmId().equals(request.realmUuid()) + || !hold.playableStateNamespaceId().equals(request.playableStateNamespaceUuid()) + || !hold.playableStateScope().equals(request.playableStateScope()) + || !hold.canonicalGameInstanceId().equals(request.canonicalGameInstanceUuid()) + || !hold.canonicalVersionId().equals(request.canonicalVersionUuid()) + || hold.expectedCatalogRevision() != request.expectedCatalogRevision() + || proof.committedPointerVersion() != request.expectedPointerVersion() + || hold.activeLifecycleEpoch() != request.expectedActiveWorldEpoch()) { + throw new IllegalArgumentException( + "Game Session proof is not the exact current committed roster target"); + } + } + + private static void requirePolicyMatches( + Request request, PublishedRealmEntryPolicySetEvidence evidence) { + if (!evidence.target().canonicalTenantId().equals(request.canonicalTenantUuid()) + || !evidence.target().canonicalVersionId().equals(request.canonicalVersionUuid())) { + throw new IllegalArgumentException("Game Design policy set changed the exact tenant/version"); + } + List matches = + evidence.policies().stream() + .filter( + policy -> + policy.policy().worldSlug().equals(request.worldSlug()) + && policy.policy().realmSlug().equals(request.realmSlug())) + .toList(); + if (matches.size() != 1) { + throw new IllegalArgumentException( + "Complete Game Design policy set lacks one exact selector"); + } + RealmEntryPolicy policy = matches.getFirst().policy(); + if (!policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !"SHARED".equals(request.playableStateScope())) { + throw new IllegalArgumentException( + "Exact route policy is not visible public-production SHARED PRESEEDED_ONLY"); + } + } + + /** Closed selectors and exact current owner counters. Account identity is not an authority. */ + public record Request( + UUID requestUuid, + UUID canonicalAccountUuid, + String targetNamespace, + UUID canonicalTenantUuid, + String worldSlug, + UUID realmUuid, + String realmSlug, + UUID playableStateNamespaceUuid, + String playableStateScope, + UUID canonicalGameInstanceUuid, + UUID canonicalVersionUuid, + long expectedCatalogRevision, + long expectedPointerVersion, + long expectedActiveWorldEpoch) { + public Request { + requireUuid(requestUuid, "requestUuid"); + requireUuid(canonicalAccountUuid, "canonicalAccountUuid"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireUuid(canonicalTenantUuid, "canonicalTenantUuid"); + requireSlug(worldSlug, "worldSlug"); + requireUuid(realmUuid, "realmUuid"); + requireSlug(realmSlug, "realmSlug"); + requireUuid(playableStateNamespaceUuid, "playableStateNamespaceUuid"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException("Only exact SHARED roster targets are supported"); + } + requireUuid(canonicalGameInstanceUuid, "canonicalGameInstanceUuid"); + requireUuid(canonicalVersionUuid, "canonicalVersionUuid"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedActiveWorldEpoch, "expectedActiveWorldEpoch"); + } + + private static void requireSlug(String value, String name) { + if (!RealmEntryPolicy.isCanonicalSlug(value)) { + throw new IllegalArgumentException(name + " must be a canonical selector"); + } + } + + private static void requireUuid(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java new file mode 100644 index 0000000000..a95362c4bf --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadGrpcCodec.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; + +/** Closed schema-1 wire mapping for the Entity-only canonical roster source read. */ +public final class CanonicalGameplayRosterOwnerReadGrpcCodec { + public static final int MAX_REQUEST_BYTES = 2 * 1024; + public static final int MAX_RESPONSE_BYTES = 2 * 1024 * 1024 + 64 * 1024; + + private static final int SCHEMA_VERSION = 1; + + private CanonicalGameplayRosterOwnerReadGrpcCodec() {} + + public static CanonicalGameplayRosterOwnerReadEvidence.Request fromRequest( + GetCanonicalGameplayRosterOwnerReadRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Gameplay roster read request exceeds its size bound"); + } + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 gameplay roster read request required"); + } + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + canonicalUuid(request.getRequestUuid(), "request_uuid"), + canonicalUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"), + request.getTargetNamespace(), + canonicalUuid(request.getCanonicalTenantUuid(), "canonical_tenant_uuid"), + request.getWorldSlug(), + canonicalUuid(request.getRealmUuid(), "realm_uuid"), + request.getRealmSlug(), + canonicalUuid(request.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"), + request.getPlayableStateScope(), + canonicalUuid(request.getCanonicalGameInstanceUuid(), "canonical_game_instance_uuid"), + canonicalUuid(request.getCanonicalVersionUuid(), "canonical_version_uuid"), + request.getExpectedCatalogRevision(), + request.getExpectedPointerVersion(), + request.getExpectedActiveWorldEpoch()); + } + + public static GetCanonicalGameplayRosterOwnerReadRequest toRequest( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetCanonicalGameplayRosterOwnerReadRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setRequestUuid(request.requestUuid().toString()) + .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantUuid(request.canonicalTenantUuid().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmUuid(request.realmUuid().toString()) + .setRealmSlug(request.realmSlug()) + .setPlayableStateNamespaceUuid(request.playableStateNamespaceUuid().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceUuid(request.canonicalGameInstanceUuid().toString()) + .setCanonicalVersionUuid(request.canonicalVersionUuid().toString()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setExpectedPointerVersion(request.expectedPointerVersion()) + .setExpectedActiveWorldEpoch(request.expectedActiveWorldEpoch()) + .build(); + } + + public static GetCanonicalGameplayRosterOwnerReadResponse toResponse( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + CanonicalGameplayRosterOwnerReadEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("Gameplay roster evidence changed the exact request"); + } + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + evidence.gameSessionOwnerProof()); + byte[] policyBytes = evidence.publishedPolicySetEvidence().canonicalBytes(); + if (proofBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || policyBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Gameplay roster owner response exceeds its size bound"); + } + var response = + GetCanonicalGameplayRosterOwnerReadResponse.newBuilder() + .setRequest(toRequest(request)) + .setGameSessionOwnerProof(ByteString.copyFrom(proofBytes)) + .setPublishedPolicySetEvidence(ByteString.copyFrom(policyBytes)) + .setAdmissionPointerSnapshotDigest(evidence.admissionPointerSnapshotDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Gameplay roster owner response exceeds its size bound"); + } + return response; + } + + public static CanonicalGameplayRosterOwnerReadEvidence fromResponse( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + GetCanonicalGameplayRosterOwnerReadResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getGameSessionOwnerProof().isEmpty() + || response.getPublishedPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete gameplay roster response required"); + } + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || response.getGameSessionOwnerProof().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || response.getPublishedPolicySetEvidence().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Gameplay roster owner response exceeds its size bound"); + } + var echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("Gameplay roster response changed the exact request"); + } + var proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + response.getGameSessionOwnerProof().toByteArray()); + var policySet = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPublishedPolicySetEvidence().toByteArray()); + return new CanonicalGameplayRosterOwnerReadEvidence( + request, response.getAdmissionPointerSnapshotDigest(), proof, policySet); + } + + private static UUID canonicalUuid(String value, String name) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, name)); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java new file mode 100644 index 0000000000..b6e7d46d8a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.common.world; + +import java.time.Instant; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Closed typed Game Session owner outcome bound to the exact World-issued hold identity. */ +public record GameSessionCanonicalInitialAdmissionOwnerProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + Outcome outcome, + Long committedPointerVersion, + Long auditEventId, + String proofDigest, + boolean positiveDurableAbort, + Instant terminalAt) { + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public enum Outcome { + PENDING, + COMMITTED, + ABORTED + } + + public GameSessionCanonicalInitialAdmissionOwnerProof { + Objects.requireNonNull(holdIdentity, "holdIdentity"); + Objects.requireNonNull(outcome, "outcome"); + if (outcome == Outcome.PENDING) { + if (committedPointerVersion != null + || auditEventId != null + || proofDigest != null + || positiveDurableAbort + || terminalAt != null) { + throw new IllegalArgumentException("PENDING is not terminal owner proof"); + } + } else if (outcome == Outcome.COMMITTED) { + requirePositive(committedPointerVersion, "committedPointerVersion"); + requirePositive(auditEventId, "auditEventId"); + requireProofDigest(proofDigest); + Objects.requireNonNull(terminalAt, "terminalAt"); + if (positiveDurableAbort) { + throw new IllegalArgumentException("COMMITTED cannot assert durable abort"); + } + } else { + if (committedPointerVersion != null || auditEventId != null) { + throw new IllegalArgumentException("ABORTED cannot carry pointer or audit commit fields"); + } + requireProofDigest(proofDigest); + Objects.requireNonNull(terminalAt, "terminalAt"); + if (!positiveDurableAbort) { + throw new IllegalArgumentException("ABORTED requires positive durable fencing"); + } + } + } + + private static void requirePositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException(field + " must be present and positive"); + } + } + + private static void requireProofDigest(String value) { + if (value == null || !PREFIXED_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("Terminal owner proof requires a prefixed SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java new file mode 100644 index 0000000000..765f33aa5f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed length-framed codec for durable Game Session canonical initial-admission outcomes. */ +public final class GameSessionCanonicalInitialAdmissionOwnerProofCodec { + private static final String SCHEMA = "game-session-canonical-initial-admission-owner-proof/v1"; + + private GameSessionCanonicalInitialAdmissionOwnerProofCodec() {} + + public static byte[] canonicalBytes(GameSessionCanonicalInitialAdmissionOwnerProof proof) { + Objects.requireNonNull(proof, "proof"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, proof.holdIdentity().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, proof.outcome().name()); + frameOptional( + output, + proof.committedPointerVersion() == null + ? null + : Long.toString(proof.committedPointerVersion())); + frameOptional( + output, proof.auditEventId() == null ? null : Long.toString(proof.auditEventId())); + frameOptional(output, proof.proofDigest()); + DraftAuthorizationFenceBinding.frame(output, proof.positiveDurableAbort() ? "true" : "false"); + frameOptional(output, proof.terminalAt() == null ? null : proof.terminalAt().toString()); + return output.toByteArray(); + } + + /** Returns the canonical owner outcome only when the complete framed value round-trips. */ + public static GameSessionCanonicalInitialAdmissionOwnerProof fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(SCHEMA); + var holdIdentity = WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(reader.bytes()); + var outcome = parseOutcome(reader.text()); + Long pointerVersion = optionalPositiveLong(reader.optionalText(), "committedPointerVersion"); + Long auditEventId = optionalPositiveLong(reader.optionalText(), "auditEventId"); + String proofDigest = reader.optionalText(); + boolean positiveDurableAbort = parseBoolean(reader.text()); + String terminalText = reader.optionalText(); + reader.requireEnd(); + Instant terminalAt = terminalText == null ? null : parseInstant(terminalText); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity, + outcome, + pointerVersion, + auditEventId, + proofDigest, + positiveDurableAbort, + terminalAt); + if (!Arrays.equals(stored, canonicalBytes(proof))) { + throw new IllegalArgumentException("Noncanonical Game Session owner proof"); + } + return proof; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof.Outcome parseOutcome(String value) { + try { + return GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.valueOf(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Unsupported canonical initial-admission owner outcome", invalid); + } + } + + private static Long optionalPositiveLong(String value, String field) { + if (value == null) { + return null; + } + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + return Long.valueOf(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static void frameOptional(ByteArrayOutputStream output, String value) { + if (value == null) { + DraftAuthorizationFenceBinding.frame(output, "ABSENT"); + } else { + DraftAuthorizationFenceBinding.frame(output, "PRESENT"); + DraftAuthorizationFenceBinding.frame(output, value); + } + } + + private static boolean parseBoolean(String value) { + return switch (value) { + case "true" -> true; + case "false" -> false; + default -> throw new IllegalArgumentException("Canonical boolean frame required"); + }; + } + + private static Instant parseInstant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Terminal timestamp is not canonical"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Terminal timestamp is not canonical", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java new file mode 100644 index 0000000000..e4a1d6289a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.common.world; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Request-bound Game Session and Game Design source evidence for non-admitting actor assignment. + * Account and assignment UUIDs are correlation selectors only; they do not establish membership, + * actor ownership, JOIN, PLAY, or gameplay admission. + */ +public record PreseededActorAssignmentOwnerReadEvidence( + Request request, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public PreseededActorAssignmentOwnerReadEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + CanonicalGameplayRosterOwnerReadEvidence.Request exactSourceRequest = + sourceRequest(request, sourceEvidence.gameSessionOwnerProof()); + if (!exactSourceRequest.equals(sourceEvidence.request())) { + throw new IllegalArgumentException( + "Game Session assignment source changed an exact request selector or owner counter"); + } + PublishedRealmEntryPolicyEvidence selected = sourceEvidence.selectedPolicyEvidence(); + String selectedDigest = rawDigest(selected.policyDigest()); + if (!request.expectedPolicyDigest().equals(selectedDigest) + || !request + .expectedPublishedReleaseBundleRef() + .equals(sourceEvidence.publishedPolicySetEvidence().publishedReleaseBundleRef())) { + throw new IllegalArgumentException( + "Game Design publication changed the exact policy or release selectors"); + } + } + + /** + * Builds the legacy exact-counter source request only from the returned owner proof. The + * assignment RPC itself never accepts pointer-version or active-epoch guesses from Entity. + */ + public static CanonicalGameplayRosterOwnerReadEvidence.Request sourceRequest( + Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(proof, "proof"); + var hold = proof.holdIdentity().request(); + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + Objects.requireNonNull(proof.committedPointerVersion(), "committedPointerVersion"), + hold.activeLifecycleEpoch()); + } + + private static String rawDigest(String value) { + if (value != null && value.matches("sha256:[0-9a-f]{64}")) { + return value.substring("sha256:".length()); + } + if (value != null && RAW_SHA256.matcher(value).matches()) { + return value; + } + throw new IllegalArgumentException("Published policy digest must be canonical SHA-256"); + } + + /** Selector-only assignment request; current pointer and World epoch counters are absent. */ + public record Request( + UUID assignmentUuid, + UUID canonicalAccountUuid, + String targetNamespace, + UUID canonicalTenantUuid, + String worldSlug, + UUID realmUuid, + String realmSlug, + UUID playableStateNamespaceUuid, + String playableStateScope, + UUID canonicalGameInstanceUuid, + UUID canonicalVersionUuid, + long expectedCatalogRevision, + String expectedPolicyDigest, + String expectedPublishedReleaseBundleRef) { + public Request { + requireUuid(assignmentUuid, "assignmentUuid"); + requireUuid(canonicalAccountUuid, "canonicalAccountUuid"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireUuid(canonicalTenantUuid, "canonicalTenantUuid"); + requireSlug(worldSlug, "worldSlug"); + requireUuid(realmUuid, "realmUuid"); + requireSlug(realmSlug, "realmSlug"); + requireUuid(playableStateNamespaceUuid, "playableStateNamespaceUuid"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException("Only exact SHARED assignment targets are supported"); + } + requireUuid(canonicalGameInstanceUuid, "canonicalGameInstanceUuid"); + requireUuid(canonicalVersionUuid, "canonicalVersionUuid"); + if (expectedCatalogRevision <= 0L) { + throw new IllegalArgumentException("expectedCatalogRevision must be positive"); + } + if (expectedPolicyDigest == null || !RAW_SHA256.matcher(expectedPolicyDigest).matches()) { + throw new IllegalArgumentException("expectedPolicyDigest must be raw lowercase SHA-256"); + } + if (expectedPublishedReleaseBundleRef == null + || expectedPublishedReleaseBundleRef.isBlank() + || !expectedPublishedReleaseBundleRef.equals(expectedPublishedReleaseBundleRef.trim()) + || expectedPublishedReleaseBundleRef.length() > MAX_RELEASE_REF_LENGTH + || expectedPublishedReleaseBundleRef.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("expectedPublishedReleaseBundleRef is incomplete"); + } + } + + private static void requireSlug(String value, String name) { + if (!RealmEntryPolicy.isCanonicalSlug(value)) { + throw new IllegalArgumentException(name + " must be a canonical selector"); + } + } + + private static void requireUuid(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java new file mode 100644 index 0000000000..079c5afc84 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadGrpcCodec.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; + +/** Closed schema-1 wire mapping for the selector-only, non-admitting assignment owner read. */ +public final class PreseededActorAssignmentOwnerReadGrpcCodec { + public static final int MAX_REQUEST_BYTES = 2 * 1024; + public static final int MAX_RESPONSE_BYTES = 2 * 1024 * 1024 + 64 * 1024; + + private static final int SCHEMA_VERSION = 1; + + private PreseededActorAssignmentOwnerReadGrpcCodec() {} + + public static PreseededActorAssignmentOwnerReadEvidence.Request fromRequest( + GetPreseededActorAssignmentOwnerReadRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Actor assignment owner request exceeds its size bound"); + } + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Closed schema-1 actor assignment owner request required"); + } + return new PreseededActorAssignmentOwnerReadEvidence.Request( + canonicalUuid(request.getAssignmentUuid(), "assignment_uuid"), + canonicalUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"), + request.getTargetNamespace(), + canonicalUuid(request.getCanonicalTenantUuid(), "canonical_tenant_uuid"), + request.getWorldSlug(), + canonicalUuid(request.getRealmUuid(), "realm_uuid"), + request.getRealmSlug(), + canonicalUuid(request.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"), + request.getPlayableStateScope(), + canonicalUuid(request.getCanonicalGameInstanceUuid(), "canonical_game_instance_uuid"), + canonicalUuid(request.getCanonicalVersionUuid(), "canonical_version_uuid"), + request.getExpectedCatalogRevision(), + request.getExpectedPolicyDigest(), + request.getExpectedPublishedReleaseBundleRef()); + } + + public static GetPreseededActorAssignmentOwnerReadRequest toRequest( + PreseededActorAssignmentOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetPreseededActorAssignmentOwnerReadRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setAssignmentUuid(request.assignmentUuid().toString()) + .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantUuid(request.canonicalTenantUuid().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmUuid(request.realmUuid().toString()) + .setRealmSlug(request.realmSlug()) + .setPlayableStateNamespaceUuid(request.playableStateNamespaceUuid().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceUuid(request.canonicalGameInstanceUuid().toString()) + .setCanonicalVersionUuid(request.canonicalVersionUuid().toString()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setExpectedPolicyDigest(request.expectedPolicyDigest()) + .setExpectedPublishedReleaseBundleRef(request.expectedPublishedReleaseBundleRef()) + .build(); + } + + public static GetPreseededActorAssignmentOwnerReadResponse toResponse( + PreseededActorAssignmentOwnerReadEvidence.Request request, + PreseededActorAssignmentOwnerReadEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("Actor assignment evidence changed the exact request"); + } + var sourceEvidence = evidence.sourceEvidence(); + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + sourceEvidence.gameSessionOwnerProof()); + byte[] policyBytes = sourceEvidence.publishedPolicySetEvidence().canonicalBytes(); + if (proofBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || policyBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Actor assignment owner response exceeds its size bound"); + } + var response = + GetPreseededActorAssignmentOwnerReadResponse.newBuilder() + .setRequest(toRequest(request)) + .setGameSessionOwnerProof(ByteString.copyFrom(proofBytes)) + .setPublishedPolicySetEvidence(ByteString.copyFrom(policyBytes)) + .setAdmissionPointerSnapshotDigest(sourceEvidence.admissionPointerSnapshotDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Actor assignment owner response exceeds its size bound"); + } + return response; + } + + public static PreseededActorAssignmentOwnerReadEvidence fromResponse( + PreseededActorAssignmentOwnerReadEvidence.Request request, + GetPreseededActorAssignmentOwnerReadResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getGameSessionOwnerProof().isEmpty() + || response.getPublishedPolicySetEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete actor assignment response required"); + } + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || response.getGameSessionOwnerProof().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES + || response.getPublishedPolicySetEvidence().size() + > CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES) { + throw new IllegalArgumentException("Actor assignment owner response exceeds its size bound"); + } + if (!request.equals(fromRequest(response.getRequest()))) { + throw new IllegalArgumentException("Actor assignment response changed the exact request"); + } + var proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + response.getGameSessionOwnerProof().toByteArray()); + var policySet = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPublishedPolicySetEvidence().toByteArray()); + var sourceRequest = PreseededActorAssignmentOwnerReadEvidence.sourceRequest(request, proof); + var sourceEvidence = + new CanonicalGameplayRosterOwnerReadEvidence( + sourceRequest, response.getAdmissionPointerSnapshotDigest(), proof, policySet); + return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); + } + + private static UUID canonicalUuid(String value, String name) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, name)); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java new file mode 100644 index 0000000000..7da2b1ad7f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.common.world; + +import java.util.Objects; +import java.util.UUID; + +/** Canonical owner-authored World room identity; never a runtime instance or private row key. */ +public record RoomTemplateRef(UUID tenantId, UUID versionId, UUID roomTemplateId) { + private static final UUID NIL = new UUID(0L, 0L); + + public RoomTemplateRef { + requireNonNil(tenantId, "tenantId"); + requireNonNil(versionId, "versionId"); + requireNonNil(roomTemplateId, "roomTemplateId"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil canonical UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java new file mode 100644 index 0000000000..67c1e2408e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java @@ -0,0 +1,391 @@ +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.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed request and immutable World-issued identity for canonical initial admission. + * + *

This carrier records acquisition identity only. It does not represent a hold status, an + * admission outcome, current lifecycle proof, an authorization grant, or an expiry authority. + */ +public final class WorldCanonicalInitialAdmissionHold { + public static final String REQUEST_SCHEMA = "world-canonical-initial-admission-hold-request/v1"; + public static final String IDENTITY_SCHEMA = "world-canonical-initial-admission-hold-identity/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern LOWER_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "realmId", + "playableStateNamespaceId", + "playableStateScope", + "canonicalGameInstanceId", + "canonicalVersionId", + "activeLifecycleEpoch", + "initialAdmissionRequestId", + "initialAdmissionRequestDigest", + "initialAdmissionOrigin", + "expectedCatalogRevision", + "expectedPriorPointerVersion"); + private static final Set IDENTITY_FIELDS = + Set.of("schema", "holdId", "holdFence", "holdBindingDigest", "requestBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private WorldCanonicalInitialAdmissionHold() {} + + /** The only initial-admission origin preconditions accepted by the first-OPEN contract. */ + public enum InitialAdmissionOrigin { + NO_PRIOR_POINTER, + EXPECT_CLOSED + } + + /** + * Complete immutable acquisition input. The supplied Game Session digest remains opaque here; + * World computes a separate hold binding digest over this complete versioned request. + */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + InitialAdmissionOrigin initialAdmissionOrigin, + long expectedCatalogRevision, + Long expectedPriorPointerVersion) { + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "Only SHARED playableStateScope is supported for initial admission"); + } + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (activeLifecycleEpoch <= 0) { + throw new IllegalArgumentException("activeLifecycleEpoch must be positive"); + } + requireBoundedText(initialAdmissionRequestId, "initialAdmissionRequestId", 128); + requireLowerSha256(initialAdmissionRequestDigest, "initialAdmissionRequestDigest"); + Objects.requireNonNull(initialAdmissionOrigin, "initialAdmissionOrigin"); + if (expectedCatalogRevision <= 0) { + throw new IllegalArgumentException("expectedCatalogRevision must be positive"); + } + if (expectedPriorPointerVersion != null && expectedPriorPointerVersion <= 0) { + throw new IllegalArgumentException( + "expectedPriorPointerVersion must be positive when present"); + } + if (initialAdmissionOrigin == InitialAdmissionOrigin.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) { + throw new IllegalArgumentException( + "NO_PRIOR_POINTER cannot carry expectedPriorPointerVersion"); + } + if (initialAdmissionOrigin == InitialAdmissionOrigin.EXPECT_CLOSED + && expectedPriorPointerVersion == null) { + throw new IllegalArgumentException("EXPECT_CLOSED requires expectedPriorPointerVersion"); + } + } + + /** Complete versioned request bytes in RFC 8785 canonical JSON form. */ + public byte[] canonicalRequestBytes() { + Map envelope = new LinkedHashMap<>(); + envelope.put("schema", REQUEST_SCHEMA); + envelope.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(envelope)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical initial-admission request cannot be encoded", impossible); + } + } + + /** World hold-binding digest; distinct from the opaque Game Session request digest. */ + public String holdBindingDigest() { + return sha256(canonicalRequestBytes()); + } + + /** Decodes only the complete exact request shape and requires canonical retained bytes. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "Canonical initial-admission request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported initial-admission request schema"); + } + JsonNode value = root.get("request"); + requireFields(value, REQUEST_FIELDS, "Canonical initial-admission request body"); + Request request = + new Request( + text(value, "targetNamespace"), + parseUuid(text(value, "canonicalTenantId"), "canonicalTenantId"), + text(value, "worldSlug"), + parseUuid(text(value, "realmId"), "realmId"), + parseUuid(text(value, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(value, "playableStateScope"), + parseUuid(text(value, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(value, "canonicalVersionId"), "canonicalVersionId"), + positiveLong(text(value, "activeLifecycleEpoch"), "activeLifecycleEpoch"), + text(value, "initialAdmissionRequestId"), + text(value, "initialAdmissionRequestDigest"), + parseOrigin(text(value, "initialAdmissionOrigin")), + positiveLong(text(value, "expectedCatalogRevision"), "expectedCatalogRevision"), + optionalPositiveLong(value, "expectedPriorPointerVersion")); + if (!Arrays.equals(stored, request.canonicalRequestBytes())) { + throw new IllegalArgumentException( + "Canonical initial-admission request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Canonical initial-admission request is invalid", invalid); + } + } + } + + /** + * Immutable acquired identity: a complete request plus World-issued non-nil hold identity and + * equality-only fence. Exact acquisition retries retain this object and its request digest. + */ + public record HoldIdentity(Request request, UUID holdId, UUID holdFence) { + public HoldIdentity { + Objects.requireNonNull(request, "request"); + requireNonNil(holdId, "holdId"); + requireNonNil(holdFence, "holdFence"); + } + + public byte[] canonicalRequestBytes() { + return request.canonicalRequestBytes(); + } + + public String holdBindingDigest() { + return request.holdBindingDigest(); + } + + /** Canonical retained identity bytes; no lifecycle or mutable hold state is represented. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", IDENTITY_SCHEMA); + value.put("holdId", holdId.toString()); + value.put("holdFence", holdFence.toString()); + value.put("holdBindingDigest", holdBindingDigest()); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(canonicalRequestBytes())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical initial-admission hold identity cannot be encoded", impossible); + } + } + + /** Decodes and verifies the entire immutable request/hold identity readback. */ + public static HoldIdentity fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, IDENTITY_FIELDS, "Canonical initial-admission hold identity"); + if (!IDENTITY_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported initial-admission hold identity schema"); + } + Request request = Request.fromStored(decodeBase64(root, "requestBytesBase64")); + String storedDigest = text(root, "holdBindingDigest"); + if (!request.holdBindingDigest().equals(storedDigest)) { + throw new IllegalArgumentException( + "Initial-admission hold binding digest differs from request"); + } + HoldIdentity identity = + new HoldIdentity( + request, + parseUuid(text(root, "holdId"), "holdId"), + parseUuid(text(root, "holdFence"), "holdFence")); + if (!Arrays.equals(stored, identity.canonicalBytes())) { + throw new IllegalArgumentException( + "Canonical initial-admission hold identity is not canonical"); + } + return identity; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Canonical initial-admission hold identity is invalid", invalid); + } + } + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("realmId", request.realmId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("activeLifecycleEpoch", Long.toString(request.activeLifecycleEpoch())); + value.put("initialAdmissionRequestId", request.initialAdmissionRequestId()); + value.put("initialAdmissionRequestDigest", request.initialAdmissionRequestDigest()); + value.put("initialAdmissionOrigin", request.initialAdmissionOrigin().name()); + value.put("expectedCatalogRevision", Long.toString(request.expectedCatalogRevision())); + value.put( + "expectedPriorPointerVersion", + request.expectedPriorPointerVersion() == null + ? null + : Long.toString(request.expectedPriorPointerVersion())); + return value; + } + + private static InitialAdmissionOrigin parseOrigin(String value) { + try { + return InitialAdmissionOrigin.valueOf(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Unsupported initialAdmissionOrigin", invalid); + } + } + + private static Long optionalPositiveLong(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null) { + throw new IllegalArgumentException(field + " must be present as text or null"); + } + if (value.isNull()) { + return null; + } + if (!value.isTextual()) { + throw new IllegalArgumentException( + field + " must be canonical positive decimal text or null"); + } + return positiveLong(value.textValue(), field); + } + + private static long positiveLong(String value, String field) { + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static UUID parseUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be non-nil"); + } + } + + private static void requireBoundedText(String value, String field, int maximumCodePoints) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints) { + throw new IllegalArgumentException(field + " must be nonempty and bounded"); + } + } + + private static void requireLowerSha256(String value, String field) { + if (value == null || !LOWER_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be lowercase 64-character SHA-256 hex"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static byte[] decodeBase64(JsonNode object, String field) { + try { + return Base64.getDecoder().decode(text(object, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be canonical base64", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Canonical hold bytes are not strict UTF-8", invalid); + } + } + + private static void requireFields(JsonNode object, Set expected, String label) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + throw new IllegalArgumentException(label + " has an invalid closed object shape"); + } + for (String name : object.propertyNames()) { + if (!expected.contains(name)) { + throw new IllegalArgumentException(label + " has an unknown field"); + } + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java new file mode 100644 index 0000000000..d3f440a6b6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java @@ -0,0 +1,286 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +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.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, canonical World evidence for the original authored start-location selector. */ +public record WorldDraftStartLocationEvidence( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest, + String receiptDigest) { + public static final String SCHEMA = "world-draft-start-location-receipt/v1"; + + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set FIELDS = + Set.of( + "schema", + "targetNamespace", + "operationId", + "requestId", + "commitId", + "authorizationFenceId", + "accountBindingDigest", + "bindingDigest", + "startLocation", + "graphDigest", + "receiptDigest"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldDraftStartLocationEvidence { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + requireCanonicalNonNilUuid(operationId, "operationId"); + requireCanonicalNonNilUuid(requestId, "requestId"); + requireCanonicalNonNilUuid(commitId, "commitId"); + requireCanonicalNonNilUuid(authorizationFenceId, "authorizationFenceId"); + requireDigest(accountBindingDigest, "accountBindingDigest"); + requireDigest(bindingDigest, "bindingDigest"); + Objects.requireNonNull(startLocation, "startLocation"); + requireDigest(graphDigest, "graphDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!receiptDigest.equals( + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest))) { + throw new IllegalArgumentException("World start-location receipt digest is invalid"); + } + } + + /** Creates the one canonical representation from the complete original receipt fields. */ + public static WorldDraftStartLocationEvidence create( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest) { + return new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest)); + } + + /** + * Decodes a complete canonical receipt and verifies its closed fields and digest. This does not + * authenticate the producer or prove the receipt's Account-bound meaning. + */ + public static WorldDraftStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(stored)) + .toString(); + JsonNode value = JSON.readTree(json); + requireFields(value, FIELDS, "World start-location receipt"); + if (!SCHEMA.equals(text(value, "schema"))) { + throw new IllegalArgumentException("Unsupported World start-location receipt schema"); + } + JsonNode selector = value.get("startLocation"); + requireFields(selector, ROOM_TEMPLATE_REF_FIELDS, "World start-location selector"); + var evidence = + new WorldDraftStartLocationEvidence( + text(value, "targetNamespace"), + parseCanonicalNonNilUuid(text(value, "operationId"), "operationId"), + parseCanonicalNonNilUuid(text(value, "requestId"), "requestId"), + parseCanonicalNonNilUuid(text(value, "commitId"), "commitId"), + parseCanonicalNonNilUuid(text(value, "authorizationFenceId"), "authorizationFenceId"), + text(value, "accountBindingDigest"), + text(value, "bindingDigest"), + new RoomTemplateRef( + parseCanonicalNonNilUuid(text(selector, "tenantId"), "selector tenantId"), + parseCanonicalNonNilUuid(text(selector, "versionId"), "selector versionId"), + parseCanonicalNonNilUuid( + text(selector, "roomTemplateId"), "selector roomTemplateId")), + text(value, "graphDigest"), + text(value, "receiptDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World start-location receipt is not canonical"); + } + return evidence; + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World start-location receipt is invalid", invalid); + } + } + + /** Returns the exact canonical receipt bytes retained by World. */ + public byte[] canonicalBytes() { + Map selector = new LinkedHashMap<>(); + selector.put("tenantId", startLocation.tenantId().toString()); + selector.put("versionId", startLocation.versionId().toString()); + selector.put("roomTemplateId", startLocation.roomTemplateId().toString()); + Map json = new LinkedHashMap<>(); + json.put("schema", SCHEMA); + json.put("targetNamespace", targetNamespace); + json.put("operationId", operationId.toString()); + json.put("requestId", requestId.toString()); + json.put("commitId", commitId.toString()); + json.put("authorizationFenceId", authorizationFenceId.toString()); + json.put("accountBindingDigest", accountBindingDigest); + json.put("bindingDigest", bindingDigest); + json.put("startLocation", selector); + json.put("graphDigest", graphDigest); + json.put("receiptDigest", receiptDigest); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(json)); + } catch (IOException impossible) { + throw new IllegalStateException("World start-location receipt cannot be encoded", impossible); + } + } + + private static String computeReceiptDigest( + String namespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef selector, + String graphDigest) { + Objects.requireNonNull(namespace, "targetNamespace"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(commitId, "commitId"); + Objects.requireNonNull(fenceId, "authorizationFenceId"); + Objects.requireNonNull(accountBindingDigest, "accountBindingDigest"); + Objects.requireNonNull(bindingDigest, "bindingDigest"); + Objects.requireNonNull(selector, "startLocation"); + Objects.requireNonNull(graphDigest, "graphDigest"); + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String segment : + new String[] { + SCHEMA, + namespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + selector.tenantId().toString(), + selector.versionId().toString(), + selector.roomTemplateId().toString(), + graphDigest + }) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static void requireCanonicalNonNilUuid(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + 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); + } + } + + private static void requireFields(JsonNode value, Set expected, String label) { + if (value == null || !value.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + if (value.size() != expected.size() + || value.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + private static String text(JsonNode value, String field) { + JsonNode child = value.get(field); + if (child == null || !child.isTextual()) { + throw new IllegalArgumentException( + "World start-location receipt field " + field + " is invalid"); + } + return child.textValue(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java new file mode 100644 index 0000000000..2db322fe14 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +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.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact World selector readback for an immutable frozen publication selection. + * + *

This evidence does not establish current Account permission, complete release evidence, + * activation, or admission. Decoding and relation checks do not authenticate the producer. The + * explicit mTLS client is responsible for authenticating World before accepting it. + */ +public record WorldPublishedStartLocationEvidence( + Request request, + byte[] selectorReceiptBytes, + byte[] originalAccountBindingBytes, + byte[] appliedResultBytes) { + public static final String SCHEMA = "world-published-start-location-evidence/v1"; + private static final int APPLIED_INTAKE_REQUEST_ID_FRAME = 13; + + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "intakeRequestId", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "worldAffectedTuples"); + private static final Set TUPLE_FIELDS = + Set.of("owner", "aggregateType", "aggregateId", "scopeType", "scopeId", "expectedEpoch"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldPublishedStartLocationEvidence { + Objects.requireNonNull(request, "request"); + selectorReceiptBytes = bytes(selectorReceiptBytes, "selectorReceiptBytes"); + originalAccountBindingBytes = bytes(originalAccountBindingBytes, "originalAccountBindingBytes"); + appliedResultBytes = bytes(appliedResultBytes, "appliedResultBytes"); + requireRelation(request, selectorReceiptBytes, originalAccountBindingBytes, appliedResultBytes); + } + + @Override + public byte[] selectorReceiptBytes() { + return selectorReceiptBytes.clone(); + } + + @Override + public byte[] originalAccountBindingBytes() { + return originalAccountBindingBytes.clone(); + } + + @Override + public byte[] appliedResultBytes() { + return appliedResultBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof WorldPublishedStartLocationEvidence that)) return false; + return request.equals(that.request) + && Arrays.equals(selectorReceiptBytes, that.selectorReceiptBytes) + && Arrays.equals(originalAccountBindingBytes, that.originalAccountBindingBytes) + && Arrays.equals(appliedResultBytes, that.appliedResultBytes); + } + + @Override + public int hashCode() { + int result = Objects.hash(request); + result = 31 * result + Arrays.hashCode(selectorReceiptBytes); + result = 31 * result + Arrays.hashCode(originalAccountBindingBytes); + result = 31 * result + Arrays.hashCode(appliedResultBytes); + return result; + } + + /** Canonical, closed durable representation; this encoding does not authenticate World. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "selectorReceiptBytesBase64", Base64.getEncoder().encodeToString(selectorReceiptBytes)); + value.put( + "originalAccountBindingBytesBase64", + Base64.getEncoder().encodeToString(originalAccountBindingBytes)); + value.put("appliedResultBytesBase64", Base64.getEncoder().encodeToString(appliedResultBytes)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World published selector evidence cannot be encoded", impossible); + } + } + + /** + * Decodes and validates retained bytes, but does not establish authenticated producer provenance. + */ + public static WorldPublishedStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(stored); + requireFields(root, EVIDENCE_FIELDS, "published World selector evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published World selector evidence schema"); + } + var evidence = + new WorldPublishedStartLocationEvidence( + parseRequest(root.get("request")), + base64(root, "selectorReceiptBytesBase64"), + base64(root, "originalAccountBindingBytesBase64"), + base64(root, "appliedResultBytesBase64")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Published World selector evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Published World selector evidence is invalid", invalid); + } + } + + private static void requireRelation( + Request request, byte[] receiptBytes, byte[] accountBytes, byte[] appliedBytes) { + var account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + if (!request.canonicalTenantId().equals(account.tenantId()) + || !request.canonicalVersionId().equals(account.versionId()) + || !request.appliedCommitId().equals(account.commitId().toString())) { + throw new IllegalArgumentException( + "Published World selection differs from original Account binding"); + } + + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(request.canonicalTenantId()) + || !draft.target().canonicalVersionId().equals(request.canonicalVersionId())) { + throw new IllegalArgumentException( + "Published World selection differs from original Draft binding"); + } + List boundTuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .sorted( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)) + .toList(); + if (!request.worldAffectedTuples().equals(boundTuples)) { + throw new IllegalArgumentException( + "Published World selection changed the complete World affected set"); + } + + var terminalRequest = + WorldDraftTerminalReadEvidence.Request.create(request.targetNamespace(), accountBytes); + var terminalReadback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + accountBytes, + appliedBytes); + var terminalResponse = + WorldDraftTerminalReadGrpcCodec.toResponse( + terminalRequest, java.util.Optional.of(terminalReadback)); + WorldDraftTerminalReadGrpcCodec.fromResponse(terminalRequest, terminalResponse); + + JsonNode applied = readApplied(appliedBytes); + if (!"APPLIED".equals(text(applied, "status"))) { + throw new IllegalArgumentException( + "Published World selector requires the original APPLIED result"); + } + if (!request.intakeRequestId().equals(appliedIntakeRequestId(applied))) { + throw new IllegalArgumentException( + "Published World selection differs from the original APPLIED intake request"); + } + byte[] resultReceipt = base64(applied, "startLocationReceiptBase64"); + if (!Arrays.equals(receiptBytes, resultReceipt)) { + throw new IllegalArgumentException( + "Published World selector differs from original APPLIED receipt"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(receiptBytes); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(account.operationId()) + || !receipt.requestId().equals(account.requestId()) + || !receipt.commitId().equals(account.commitId()) + || !receipt.authorizationFenceId().equals(account.fenceId()) + || !receipt.accountBindingDigest().equals(prefixedSha256(accountBytes)) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(request.canonicalTenantId()) + || !receipt.startLocation().versionId().equals(request.canonicalVersionId()) + || !receipt.graphDigest().equals(text(applied, "graphDigest"))) { + throw new IllegalArgumentException( + "Published World selector receipt differs from selected APPLIED commit"); + } + } + + private static JsonNode readApplied(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + return JSON.readTree(json); + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World APPLIED result is invalid", invalid); + } + } + + /** Reads the immutable intake identity from the exact operation frame already codec-validated. */ + private static UUID appliedIntakeRequestId(JsonNode applied) { + ByteBuffer operation = ByteBuffer.wrap(base64(applied, "operationBytesBase64")); + String intakeRequestId = null; + for (int frameIndex = 0; frameIndex <= APPLIED_INTAKE_REQUEST_ID_FRAME; frameIndex++) { + if (operation.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("World APPLIED operation frame is truncated"); + } + int frameLength = operation.getInt(); + if (frameLength < 0 || frameLength > operation.remaining()) { + throw new IllegalArgumentException("World APPLIED operation frame has an invalid length"); + } + byte[] frame = new byte[frameLength]; + operation.get(frame); + if (frameIndex == 0 + && !"world-draft-terminal-operation/v1" + .equals(new String(frame, StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Unsupported World APPLIED operation frame schema"); + } + if (frameIndex == APPLIED_INTAKE_REQUEST_ID_FRAME) { + try { + intakeRequestId = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(frame)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "World APPLIED intake request frame is invalid", invalid); + } + } + } + return parseUuid(intakeRequestId, "APPLIED intakeRequestId"); + } + + private static String prefixedSha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "published World selector request"); + JsonNode tuples = node.get("worldAffectedTuples"); + if (tuples == null || !tuples.isArray()) { + throw new IllegalArgumentException("World affected tuple array is required"); + } + List affected = new ArrayList<>(); + for (JsonNode tuple : tuples) { + requireFields(tuple, TUPLE_FIELDS, "World affected tuple"); + affected.add( + new OwnedAffectedTuple( + text(tuple, "owner"), + text(tuple, "aggregateType"), + text(tuple, "aggregateId"), + text(tuple, "scopeType"), + text(tuple, "scopeId"), + text(tuple, "expectedEpoch"))); + } + Request decoded = + new Request( + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + parseUuid(text(node, "intakeRequestId"), "intakeRequestId"), + parseUuid(text(node, "publicationFence"), "publicationFence"), + text(node, "publicationRequestId"), + text(node, "requestDigest"), + positiveLong(text(node, "versionStateEpoch"), "versionStateEpoch"), + text(node, "publishWorkflowId"), + text(node, "appliedCommitId"), + text(node, "contentDigest"), + intValue(node, "digestSchemaVersion"), + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("intakeRequestId", request.intakeRequestId().toString()); + value.put("publicationFence", request.publicationFence().toString()); + value.put("publicationRequestId", request.publicationRequestId()); + value.put("requestDigest", request.requestDigest()); + value.put("versionStateEpoch", Long.toString(request.versionStateEpoch())); + value.put("publishWorkflowId", request.publishWorkflowId()); + value.put("appliedCommitId", request.appliedCommitId()); + value.put("contentDigest", request.contentDigest()); + value.put("digestSchemaVersion", request.digestSchemaVersion()); + value.put( + "worldAffectedTuples", + request.worldAffectedTuples().stream() + .map( + tuple -> { + Map item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + return item; + }) + .toList()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static byte[] bytes(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(name + " is required"); + } + return value.clone(); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static UUID parseUuid(String value, String label) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical UUID", invalid); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact transport-neutral immutable selection input. */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List worldAffectedTuples) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + requireUuid(intakeRequestId, "intakeRequestId"); + requireUuid(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + if (versionStateEpoch <= 0) + throw new IllegalArgumentException("versionStateEpoch must be positive"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException("Unsupported World digest schema version"); + } + Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); + List ordered = new ArrayList<>(worldAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + if (ordered.stream().distinct().count() != ordered.size()) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + worldAffectedTuples = List.copyOf(ordered); + } + + private static void requireUuid(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + + private static void requireSha256(String value, String name) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be 64 lowercase hexadecimal digits"); + } + } + } + + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("Published selector tuples must name WORLD_MANAGEMENT"); + } + requireTupleText(aggregateType, "aggregateType"); + requireTupleText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException("scopeType and scopeId must both be present or absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + + private static void requireTupleText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java new file mode 100644 index 0000000000..faaa5407b1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationAffectedTuple; + +/** Closed wire mapping and exact request-echo validation for the World selector read. */ +public final class WorldPublishedStartLocationGrpcCodec { + private WorldPublishedStartLocationGrpcCodec() {} + + public static ReadWorldPublishedStartLocationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var builder = + ReadWorldPublishedStartLocationRequest.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** + * Decodes only after the World receiver authenticates its exact same-namespace Game Design peer. + */ + public static Request fromRequest(ReadWorldPublishedStartLocationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldPublishedStartLocationRequest"); + if (request.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector read schema version"); + } + return toEvidenceRequest( + request.getTargetNamespace(), + request.getCanonicalTenantId(), + request.getCanonicalVersionId(), + request.getIntakeRequestId(), + request.getPublicationFence(), + request.getPublicationRequestId(), + request.getRequestDigest(), + request.getVersionStateEpoch(), + request.getPublishWorkflowId(), + request.getAppliedCommitId(), + request.getContentDigest(), + request.getDigestSchemaVersion(), + request.getWorldAffectedTuplesList()); + } + + public static ReadWorldPublishedStartLocationResponse toResponse( + Request request, WorldPublishedStartLocationEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World selector evidence differs from exact selection request"); + } + var builder = + ReadWorldPublishedStartLocationResponse.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()) + .setSelectorReceiptBytes(ByteString.copyFrom(evidence.selectorReceiptBytes())) + .setOriginalAccountBindingBytes( + ByteString.copyFrom(evidence.originalAccountBindingBytes())) + .setAppliedResultBytes(ByteString.copyFrom(evidence.appliedResultBytes())); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** Validates the complete echoed capture tuple and all three exact retained World byte values. */ + public static WorldPublishedStartLocationEvidence fromResponse( + Request request, ReadWorldPublishedStartLocationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldPublishedStartLocationResponse"); + if (response.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector response schema version"); + } + Request echoed = + toEvidenceRequest( + response.getTargetNamespace(), + response.getCanonicalTenantId(), + response.getCanonicalVersionId(), + response.getIntakeRequestId(), + response.getPublicationFence(), + response.getPublicationRequestId(), + response.getRequestDigest(), + response.getVersionStateEpoch(), + response.getPublishWorkflowId(), + response.getAppliedCommitId(), + response.getContentDigest(), + response.getDigestSchemaVersion(), + response.getWorldAffectedTuplesList()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "World published selector response changed exact selection request"); + } + if (response.getSelectorReceiptBytes().isEmpty() + || response.getOriginalAccountBindingBytes().isEmpty() + || response.getAppliedResultBytes().isEmpty()) { + throw new IllegalArgumentException( + "World published selector response lacks retained evidence bytes"); + } + return new WorldPublishedStartLocationEvidence( + request, + response.getSelectorReceiptBytes().toByteArray(), + response.getOriginalAccountBindingBytes().toByteArray(), + response.getAppliedResultBytes().toByteArray()); + } + + private static Request toEvidenceRequest( + String namespace, + String tenant, + String version, + String intakeRequest, + String publicationFence, + String publicationRequest, + String requestDigest, + long versionStateEpoch, + String workflow, + String appliedCommit, + String contentDigest, + int digestSchema, + java.util.List tuples) { + var affected = + tuples.stream().map(WorldPublishedStartLocationGrpcCodec::fromWireTuple).toList(); + Request decoded = + new Request( + namespace, + canonicalUuid(tenant, "canonicalTenantId"), + canonicalUuid(version, "canonicalVersionId"), + canonicalUuid(intakeRequest, "intakeRequestId"), + canonicalUuid(publicationFence, "publicationFence"), + publicationRequest, + requestDigest, + versionStateEpoch, + workflow, + appliedCommit, + contentDigest, + digestSchema, + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static WorldPublishedStartLocationAffectedTuple toWireTuple(OwnedAffectedTuple tuple) { + return WorldPublishedStartLocationAffectedTuple.newBuilder() + .setOwner(tuple.owner()) + .setAggregateType(tuple.aggregateType()) + .setAggregateId(tuple.aggregateId()) + .setScopeType(tuple.scopeType()) + .setScopeId(tuple.scopeId()) + .setExpectedEpoch(tuple.expectedEpoch()) + .build(); + } + + private static OwnedAffectedTuple fromWireTuple(WorldPublishedStartLocationAffectedTuple tuple) { + requireNoUnknownFields(tuple, "WorldPublishedStartLocationAffectedTuple"); + return new OwnedAffectedTuple( + tuple.getOwner(), + tuple.getAggregateType(), + tuple.getAggregateId(), + tuple.getScopeType(), + tuple.getScopeId(), + tuple.getExpectedEpoch()); + } + + private static java.util.UUID canonicalUuid(String value, String label) { + try { + java.util.UUID parsed = java.util.UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new java.util.UUID(0L, 0L))) { + 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); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java new file mode 100644 index 0000000000..52ffc3f2df --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.common.account; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountActorStagingEligibilityEvidenceTest { + private static final String NAMESPACE = "test"; + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TENANT_ID = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); + private static final UUID TENANT_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final Instant OBSERVED_AT = Instant.parse("2026-10-08T00:00:00.123456789Z"); + + @Test + void sealsCurrentActiveMembershipAsStagingEligibleWithSeparateDigests() { + AccountActorStagingEligibilityEvidence evidence = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); + + assertThat(evidence.decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.authoritySnapshotDigest()).matches("[0-9a-f]{64}"); + assertThat(evidence.eligibilityDecisionDigest()).matches("[0-9a-f]{64}"); + assertThat(evidence.authoritySnapshotDigest()) + .isNotEqualTo(evidence.eligibilityDecisionDigest()); + assertThat(evidence.observedAt()).isEqualTo(OBSERVED_AT); + } + + @Test + void accountOrMembershipEligibilityFailureIsNotOverstated() { + assertThat(seal("SECURITY_LOCKED", "ACTIVE", true, REQUEST_ID).decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + assertThat(seal("ACTIVE", "INACTIVE", false, REQUEST_ID).decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + assertThat(seal("ACTIVE", "ACTIVE", false, REQUEST_ID).decision()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE); + } + + @Test + void authorityAndDecisionDigestsBindDifferentRequestEvidence() { + AccountActorStagingEligibilityEvidence first = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); + AccountActorStagingEligibilityEvidence second = + seal("ACTIVE", "ACTIVE", true, UUID.fromString("44444444-4444-4444-8444-444444444444")); + + assertThat(second.authoritySnapshotDigest()).isNotEqualTo(first.authoritySnapshotDigest()); + assertThat(second.eligibilityDecisionDigest()).isNotEqualTo(first.eligibilityDecisionDigest()); + } + + @Test + void rejectsTamperedAuthorityAndNonpositiveMembershipVersion() { + AccountActorStagingEligibilityEvidence evidence = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); + + assertThatThrownBy( + () -> + new AccountActorStagingEligibilityEvidence( + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.requestId(), + evidence.canonicalAccountId(), + evidence.canonicalTenantId(), + evidence.purpose(), + evidence.currentness(), + evidence.observedAt(), + evidence.decision(), + evidence.accountUuidProvenance(), + evidence.accountLifecycleState(), + evidence.membershipLifecycleState(), + evidence.gameplayAdmissionAllowed(), + evidence.membershipAuthorityProvenance(), + evidence.membershipVersion() + 1L, + evidence.membershipAuthorityGeneration(), + evidence.tenantProvenanceKind(), + evidence.tenantSourceOperationId(), + evidence.tenantProvenanceDigest(), + evidence.membershipEventSequence(), + evidence.membershipEventId(), + evidence.membershipEventDigest(), + evidence.lastTransitionInvalidated(), + evidence.eligibilityDecisionDigest(), + evidence.authoritySnapshotDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Authority snapshot digest does not match its fields"); + + assertThatThrownBy( + () -> + AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + OBSERVED_AT, + "ACCOUNT_V29_MIGRATION", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 0L, + 1L, + "FRESH_GAME_DESIGN", + TENANT_OPERATION_ID, + "sha256:" + "a".repeat(64), + 1L, + MEMBERSHIP_EVENT_ID, + "sha256:" + "b".repeat(64), + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Positive membership authority counters are required"); + } + + private static AccountActorStagingEligibilityEvidence seal( + String accountLifecycle, String membershipLifecycle, boolean admission, UUID requestId) { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + requestId, + ACCOUNT_ID, + TENANT_ID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + OBSERVED_AT, + "ACCOUNT_V29_MIGRATION", + accountLifecycle, + membershipLifecycle, + admission, + "EXPLICIT_JOIN", + 2L, + 1L, + "FRESH_GAME_DESIGN", + TENANT_OPERATION_ID, + "sha256:" + "a".repeat(64), + 1L, + MEMBERSHIP_EVENT_ID, + "sha256:" + "b".repeat(64), + false); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java new file mode 100644 index 0000000000..736b2bdac7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftBaseReferenceTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class DraftBaseReferenceTest { + @Test + void closedVersionedGrammarDistinguishesReceiptFromCommit() { + String id = "abcde123-1234-5678-abcd-123456789abc"; + assertThat(DraftBaseReference.SCHEMA).isEqualTo("game-design-draft-base-reference/v1"); + var genesis = DraftBaseReference.parse("genesis:" + id); + assertThat(genesis.kind()).isEqualTo(DraftBaseReference.Kind.GENESIS); + assertThat(genesis.identity()).isEqualTo(UUID.fromString(id)); + assertThat(genesis.canonicalValue()).isEqualTo("genesis:" + id); + var authored = DraftBaseReference.parse(id); + assertThat(authored.kind()).isEqualTo(DraftBaseReference.Kind.AUTHORED_COMMIT); + assertThat(authored.canonicalValue()).isEqualTo(id); + assertThat(genesis).isNotEqualTo(authored); + } + + @Test + void rejectsEveryNoncanonicalOrUnknownForm() { + String id = "abcde123-1234-5678-abcd-123456789abc"; + for (String value : + List.of( + "", + " ", + "genesis:", + "GENESIS:" + id, + "commit:" + id, + id.toUpperCase(java.util.Locale.ROOT), + "genesis:" + id.toUpperCase(java.util.Locale.ROOT), + " " + id, + id + "\n", + "genesis:" + id + ":extra", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "genesis:00000000-0000-0000-0000-000000000000")) { + assertThatThrownBy(() -> DraftBaseReference.parse(value)) + .isInstanceOf(IllegalArgumentException.class); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..35bf6e7387 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -0,0 +1,891 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +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.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import org.junit.jupiter.api.Test; + +public class WorldDraftTerminalReadGrpcCodecTest { + 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(); + + @Test + void requestCarriesAndDefensivelyRetainsTheCompleteOriginalBinding() { + byte[] original = originalBinding(); + var request = + new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), original); + original[0] ^= 1; + + var wire = WorldDraftTerminalReadGrpcCodec.toRequest(request); + var decoded = WorldDraftTerminalReadGrpcCodec.fromRequest(wire); + assertThat(decoded).isEqualTo(request); + assertThat(decoded.originalAccountBinding()).containsExactly(request.originalAccountBinding()); + assertThat( + WorldDraftTerminalReadEvidence.Request.create("test", request.originalAccountBinding()) + .readRequestId()) + .isNotEqualTo(request.accountBinding().operationId()); + } + + @Test + void unknownIsExplicitAndCarriesNoOwnerResult() { + var request = request(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()); + + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.ownerReadback()).isEmpty(); + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); + assertThat(response.getOwnerReadbackBytes()).isEmpty(); + } + + @Test + void exactAbortMustBeWorldAndMustEchoEveryRequestFieldAndOriginalBinding() { + var request = request(); + var binding = request.accountBinding(); + var abort = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1, 2, 3}); + + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(abort)); + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + + var decodedAbort = evidence.ownerReadback().orElseThrow(); + assertThat(decodedAbort.canonicalBytes()).containsExactly(abort.canonicalBytes()); + assertThat(decodedAbort.fullBinding()).containsExactly(request.originalAccountBinding()); + assertThat(decodedAbort.result()).containsExactly(1, 2, 3); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.toResponse( + request, + Optional.of( + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1})))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World terminal response"); + + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setReadRequestId(uuid("77777777-7777-4777-8777-777777777777").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact read request"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact read request"); + } + + @Test + void rejectsUnknownFieldsAndContradictoryStatusPayloads() { + var request = request(); + var encoded = WorldDraftTerminalReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromRequest( + encoded.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + ReadWorldDraftTerminalOutcomeResponse unknownWithBytes = + WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()).toBuilder() + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build(); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, unknownWithBytes)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UNKNOWN"); + } + + @Test + void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSubstitution() { + var request = request(); + var committed = committedReadback(request); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); + assertThat( + WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow() + .canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setStatus( + WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .build())) + .hasMessageContaining("status differs"); + var abort = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1}); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(abort.canonicalBytes())) + .build())) + .hasMessageContaining("status differs"); + var wrongOwner = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + committed.result()); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(wrongOwner.canonicalBytes())) + .build())) + .hasMessageContaining("World terminal response"); + var substituted = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1, 2, 3}); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build())) + .hasMessageContaining("substituted canonical APPLIED result"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) + .hasMessageContaining("changed the exact read request"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearOwnerReadbackBytes().build())) + .hasMessageContaining("bytes are required"); + } + + @Test + void committedCarrierRejectsEmbeddedOperationGraphDigestEpochAndUnknownFieldChanges() + throws Exception { + var request = request(); + var committed = committedReadback(request); + var mapper = new tools.jackson.databind.ObjectMapper(); + for (String field : + List.of("operationBytesBase64", "graphDigest", "appliedEpochs", "unknown")) { + var json = (tools.jackson.databind.node.ObjectNode) mapper.readTree(committed.result()); + switch (field) { + case "operationBytesBase64" -> + json.put(field, java.util.Base64.getEncoder().encodeToString(new byte[] {1})); + case "graphDigest" -> json.put(field, "sha256:" + "0".repeat(64)); + case "appliedEpochs" -> json.set(field, mapper.createArrayNode()); + default -> json.put(field, "unsupported"); + } + var bytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(json)); + var changed = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + bytes); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(changed))) + .hasMessageContaining("substituted canonical APPLIED result"); + } + } + + @Test + void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclaration() + throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + byte[] graphBytes = + Base64.getDecoder().decode(object(committed.result()).get("graphBytesBase64").textValue()); + assertThat(java.util.Arrays.equals(graphBytes, canonical(JSON.readTree(graphBytes)))).isFalse(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); + assertThat( + WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow() + .canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + } + + @Test + void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + var result = object(committed.result()); + result.put("graphDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(request, committed, canonical(result)); + + result = object(committed.result()); + byte[] malformedGraph = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + malformedGraph[0] = (byte) 0xff; + String graphDigest = sha256(malformedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(malformedGraph)); + result.put("graphDigest", graphDigest); + var draft = + DraftCommitBinding.fromStored( + new String(request.accountBinding().gameDesignBinding(), StandardCharsets.UTF_8), + request.accountBinding().inputDigest()); + var changedReceipt = receipt(request, draft, graphDigest); + byte[] changedReceiptBytes = canonical(changedReceipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + assertResultRejected(request, committed, canonical(result)); + } + + @Test + void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + for (java.util.function.Consumer change : + List.>of( + receipt -> + selector(receipt) + .put("roomTemplateId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + selector(receipt) + .put("tenantId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + selector(receipt) + .put("versionId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put("requestId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put("commitId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put( + "authorizationFenceId", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> receipt.put("accountBindingDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("bindingDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("graphDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("receiptDigest", "sha256:" + "0".repeat(64)))) { + assertReceiptChangeRejected(request, committed, change); + } + assertReceiptChangeRejected( + request, committed, receipt -> receipt.put("unsupported", "new-field")); + var changedTopLevel = object(committed.result()); + changedTopLevel.put("unsupported", "new-field"); + assertResultRejected(request, committed, canonical(changedTopLevel)); + changedTopLevel = object(committed.result()); + changedTopLevel.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(request, committed, canonical(changedTopLevel)); + } + + @Test + void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + var result = object(committed.result()); + byte[] receiptBytes = + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); + String receiptJson = new String(receiptBytes, StandardCharsets.UTF_8); + result.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString((" " + receiptJson).getBytes(StandardCharsets.UTF_8))); + assertResultRejected(request, committed, canonical(result)); + + result = object(committed.result()); + byte[] graphBytes = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + var graph = object(graphBytes); + var rows = (tools.jackson.databind.node.ArrayNode) graph.get("rows"); + for (tools.jackson.databind.JsonNode row : rows) { + if ("ROOM".equals(row.get("mapping").get("family").textValue())) { + ((tools.jackson.databind.node.ObjectNode) row.get("mapping")) + .put("template_id", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()); + } + } + byte[] changedGraph = canonical(graph); + String graphDigest = sha256(changedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(changedGraph)); + result.put("graphDigest", graphDigest); + var binding = request.accountBinding(); + var commitBinding = + DraftCommitBinding.fromStored( + new String(binding.gameDesignBinding(), StandardCharsets.UTF_8), binding.inputDigest()); + var changedReceipt = receipt(request, commitBinding, graphDigest); + byte[] changedReceiptBytes = canonical(JSON.valueToTree(changedReceipt)); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + assertResultRejected(request, committed, canonical(result)); + } + + @Test + void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws Exception { + var declaredRequest = freshGraphRequest(); + var declaredResult = committedReadback(declaredRequest, true); + var downgraded = object(declaredResult.result()); + downgraded.put("schema", "world-draft-graph-applied/v1"); + downgraded.remove("startLocationReceiptBase64"); + downgraded.remove("startLocationReceiptDigest"); + assertResultRejected(declaredRequest, declaredResult, canonical(downgraded)); + + var historicalRequest = request(); + var historicalResult = committedReadback(historicalRequest); + var upgraded = object(historicalResult.result()); + upgraded.put("schema", "world-draft-graph-applied/v2"); + upgraded.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); + upgraded.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(historicalRequest, historicalResult, canonical(upgraded)); + } + + /** + * Transport-only stipulated carrier; real persistence and six-family semantics are World proof. + */ + static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request) { + try { + return committedReadback(request, false); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + + 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 request() { + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), originalBinding()); + } + + private static byte[] originalBinding() { + DraftCommitBinding draft = + 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", REVISION_ID, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + return accountBinding(draft); + } + + /** Test-only exact fresh graph request shared with the published selector carrier proof. */ + public static WorldDraftTerminalReadEvidence.Request + freshGraphRequestForStartLocationEvidenceTest() throws Exception { + return freshGraphRequest(); + } + + /** Test-only complete World APPLIED-v2 readback for the exact fresh graph request. */ + public static DraftAuthorizationFenceBinding.OwnerReadback + committedFreshGraphReadbackForStartLocationEvidenceTest( + WorldDraftTerminalReadEvidence.Request request) { + try { + return committedReadback(request, true); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + + 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 tools.jackson.databind.node.ObjectNode selector( + tools.jackson.databind.node.ObjectNode receipt) { + return (tools.jackson.databind.node.ObjectNode) receipt.get("startLocation"); + } + + private static void assertReceiptChangeRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + java.util.function.Consumer change) + throws Exception { + var result = object(committed.result()); + byte[] bytes = Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); + var receipt = object(bytes); + change.accept(receipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(canonical(receipt))); + assertResultRejected(request, committed, canonical(result)); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes) { + var baseline = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + var substituted = readbackWithResult(committed, resultBytes); + var response = + baseline.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build(); + assertThatThrownBy(() -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback readbackWithResult( + DraftAuthorizationFenceBinding.OwnerReadback original, byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.fullBinding(), + result); + } + + private static tools.jackson.databind.node.ObjectNode object(byte[] bytes) throws Exception { + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(bytes); + } + + 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); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java new file mode 100644 index 0000000000..9eadf7f472 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class PublishedRealmEntryPolicyEvidenceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 42, + "tenant-42", + 7, + "tenant-42", + "NEW_GAME_ROW"); + private static final UUID POLICY_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_COMMIT_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID SOURCE_REVISION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void policyDigestMatchesTheOwnerKnownVectorForTheActualReleaseIdentity() { + RealmEntryPolicy policy = policy("world", "World", "main", "Main", true, true); + + String digest = + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy); + + // Shared carrier vector copied from the independent Game Design owner implementation proof. + assertThat(digest) + .isEqualTo("sha256:1cb51d94ec2825d1d598fa30c197e6ce52d23b8a62106b04babcaafc92be2f47"); + } + + @Test + void policyDigestChangesWhenAnyAuthoredOrActualReleaseIdentityChanges() { + RealmEntryPolicy policy = policy("world", "World", "main", "Main", true, true); + String original = + digest(policy, TARGET, 12, "bundle:exact", "workflow-123", SOURCE_REVISION_ID); + + assertThat(digest(policy, TARGET, 13, "bundle:exact", "workflow-123", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + assertThat(digest(policy, TARGET, 12, "bundle:changed", "workflow-123", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + assertThat(digest(policy, TARGET, 12, "bundle:exact", "workflow-changed", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + var changedTarget = + new TargetProof( + TARGET.canonicalTenantId(), + TARGET.canonicalVersionId(), + TARGET.gameDesignVersionRowId(), + TARGET.gameDesignVersionTenantKey(), + TARGET.sourceGameRowId() + 1, + TARGET.sourceGameTenantKey(), + TARGET.sourceProvenanceKind()); + assertThat( + digest(policy, changedTarget, 12, "bundle:exact", "workflow-123", SOURCE_REVISION_ID)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "c".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "c".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + UUID.fromString("66666666-6666-4666-8666-666666666666"), + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + UUID.fromString("77777777-7777-4777-8777-777777777777"), + SOURCE_REVISION_ID, + "main-policy-v1", + policy)) + .isNotEqualTo(original); + assertThat( + digest( + policy, + TARGET, + 12, + "bundle:exact", + "workflow-123", + UUID.fromString("88888888-8888-4888-8888-888888888888"))) + .isNotEqualTo(original); + assertThat( + PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + TARGET, + 12, + "bundle:exact", + "sha256:" + "a".repeat(64), + "workflow-123", + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v2", + policy)) + .isNotEqualTo(original); + assertThat( + digest( + policy("world", "World", "main", "Main Changed", true, true), + TARGET, + 12, + "bundle:exact", + "workflow-123", + SOURCE_REVISION_ID)) + .isNotEqualTo(original); + } + + @Test + void childEvidenceRetainsTheCanonicalPolicyAndRejectsMalformedIdentity() { + RealmEntryPolicy policy = policy("world", "World", "main", "Main", true, true); + String digest = digest(policy, TARGET, 12, "bundle:exact", "workflow-123", SOURCE_REVISION_ID); + var evidence = + new PublishedRealmEntryPolicyEvidence( + POLICY_ID, SOURCE_COMMIT_ID, SOURCE_REVISION_ID, "main-policy-v1", policy, digest); + + assertThat(evidence.policy().canonicalJson()).isEqualTo(policy.canonicalJson()); + assertThat(evidence.policyId()).isEqualTo(POLICY_ID); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicyEvidence( + POLICY_ID, + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy, + "not-a-digest")); + } + + private static String digest( + RealmEntryPolicy policy, + TargetProof target, + int versionNumber, + String bundleRef, + String workflow, + UUID sourceRevisionId) { + return PublishedRealmEntryPolicyEvidence.calculateDigest( + POLICY_ID, + target, + versionNumber, + bundleRef, + "sha256:" + "a".repeat(64), + workflow, + "sha256:" + "b".repeat(64), + SOURCE_COMMIT_ID, + sourceRevisionId, + "main-policy-v1", + policy); + } + + private static RealmEntryPolicy policy( + String world, + String worldName, + String realm, + String realmName, + boolean visible, + boolean publicProduction) { + return RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"" + + world + + "\",\"worldDisplayName\":\"" + + worldName + + "\",\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"" + + realmName + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + publicProduction + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + MAPPER); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java new file mode 100644 index 0000000000..523aafbebe --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java @@ -0,0 +1,398 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceEvidenceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REGISTRATION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String TENANT_SLUG = "north-star"; + private static final String WORLD_SLUG = "violet-wilds"; + private static final String DISPLAY_NAME = "Café 🐉"; + private static final long SOURCE_GAME_ROW_ID = 42L; + private static final String SOURCE_GAME_TENANT_KEY = "legacy-game-tenant-42"; + private static final String PROVENANCE = "RETAINED_GAME_V29"; + + @Test + void acceptsClosedNewAndRetainedSourceEvidenceAndRecomputesBothDigests() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + } + + @Test + void acceptsMaximumSelectorBytesAndDisplayCodePoints() { + String maximumTenantSlug = "a".repeat(120); + String maximumWorldSlug = "b".repeat(120); + String maximumDisplayName = "é".repeat(100); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_ID, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + + assertThat( + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE, + evidenceDigest) + .worldDisplayName()) + .hasSize(100); + } + + @Test + void rejectsUnsupportedVersionMalformedIdentitySelectorsAndDisplayName() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertInvalid( + 2, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + "bad.namespace", + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + new UUID(0L, 0L), + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + new UUID(0L, 0L), + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + new UUID(0L, 0L), + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "North-Star", + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "a".repeat(121), + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + "bad_slug", + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + " ", + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "😀".repeat(101), + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "bad" + (char) 0xd800, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertThat(valid.worldDisplayName()).isEqualTo(DISPLAY_NAME); + } + + @Test + void rejectsChangedRequestReceiptSourceBoundsAndUnknownProvenance() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + "sha256:" + "0".repeat(64), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Request digest"); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + "sha256:" + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Evidence digest"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + 0L, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "x".repeat(37), + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "bad" + (char) 0xd800, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "OTHER"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "RETAINED_GAME_V30"); + } + + private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + provenanceKind, + evidenceDigest); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + new AuthoredWorldSourceEvidence( + schemaVersion, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + }) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java new file mode 100644 index 0000000000..0be76125d2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class RuntimeTenantIdentityEvidenceTest { + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void acceptsNewAndRetainedOwnerEvidence() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + } + + @Test + void rejectsUnsupportedOrIncompleteOwnerEvidence() { + RuntimeTenantIdentityEvidence valid = evidence("NEW_GAME_ROW"); + assertInvalid( + 2, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + "test.invalid", + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + new UUID(0L, 0L), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + new UUID(0L, 0L), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + 0, + valid.sourceGameTenantKey(), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + " ", + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "x".repeat(37), + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + "invalid-" + (char) 0xd800, + valid.provenanceKind()); + assertInvalid( + 1, + valid.targetNamespace(), + valid.requestId(), + valid.canonicalTenantId(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + "UNKNOWN"); + } + + private static RuntimeTenantIdentityEvidence evidence(String provenanceKind) { + return new RuntimeTenantIdentityEvidence( + 1, "test", REQUEST_ID, TENANT_ID, 42L, "source-game-key-42", provenanceKind); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> + new RuntimeTenantIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java new file mode 100644 index 0000000000..32ae8a3292 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java @@ -0,0 +1,285 @@ +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.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRosterOwnerReadEvidenceTest { + private static final String TARGET_NAMESPACE = "gameplay"; + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REALM = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID PLAYABLE_NAMESPACE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID INSTANCE = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-08T03:04:05Z"); + + @Test + void acceptsExactCommittedWorldHoldAndCompletePreseededPolicySet() throws Exception { + var expected = fixture(); + assertThat(expected.gameSessionOwnerProof().outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(expected.gameSessionOwnerProof().holdIdentity().request().canonicalTenantId()) + .isEqualTo(expected.request().canonicalTenantUuid()); + assertThat(expected.publishedPolicySetEvidence().policyCount()).isEqualTo(1); + assertThat(expected.selectedPolicyEvidence().policy().entryPolicy()) + .isEqualTo( + net.firedevops.firemud.common.publication.RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + } + + @Test + void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception { + var good = fixture(); + var pending = pendingProof(good.gameSessionOwnerProof().holdIdentity()); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + good.request(), "1".repeat(64), pending, good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var staleRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + good.request().requestUuid(), + ACCOUNT, + TARGET_NAMESPACE, + good.request().canonicalTenantUuid(), + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + good.request().canonicalVersionUuid(), + 71L, + 74L, + 82L); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + staleRequest, + good.admissionPointerSnapshotDigest(), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var wrongRealm = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + good.request().requestUuid(), + ACCOUNT, + TARGET_NAMESPACE, + good.request().canonicalTenantUuid(), + "earth", + REALM, + "unpublished", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + good.request().canonicalVersionUuid(), + 71L, + 73L, + 82L); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + wrongRealm, + good.admissionPointerSnapshotDigest(), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + good.request(), + "A".repeat(64), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void grpcCodecRoundTripsCompleteProofAndRejectsUnknownPartialOrChangedEcho() throws Exception { + var evidence = fixture(); + var request = evidence.request(); + var wireRequest = CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request); + assertThat(CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var response = CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request, evidence); + assertThat(response.hasRequest()).isTrue(); + assertThat(response.getRequest().getCanonicalAccountUuid()).isEqualTo(ACCOUNT.toString()); + assertThat(response.getAdmissionPointerSnapshotDigest()) + .isEqualTo(evidence.admissionPointerSnapshotDigest()); + assertThat(CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(evidence); + + var unknownRequest = + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setCanonicalAccountUuid("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setExpectedPointerVersion(Long.MAX_VALUE * -1L) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setWorldSlug("x".repeat(3000)).build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, GetCanonicalGameplayRosterOwnerReadResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setCanonicalAccountUuid( + uuid("99999999-9999-4999-8999-999999999999").toString()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 101, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, response.toBuilder().clearPublishedPolicySetEvidence().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder().setAdmissionPointerSnapshotDigest("A".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFrom( + new byte + [CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var pending = pendingProof(evidence.gameSessionOwnerProof().holdIdentity()); + var nonCommittedResponse = + GetCanonicalGameplayRosterOwnerReadResponse.newBuilder() + .setRequest(wireRequest) + .setGameSessionOwnerProof( + ByteString.copyFrom( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(pending))) + .setPublishedPolicySetEvidence( + ByteString.copyFrom(evidence.publishedPolicySetEvidence().canonicalBytes())) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, nonCommittedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayRosterOwnerReadEvidence fixture() throws Exception { + var set = PublishedRealmEntryPolicySetEvidenceTest.preseededSetFixture(); + UUID tenant = set.target().canonicalTenantId(); + UUID version = set.target().canonicalVersionId(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var holdIdentity = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT); + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("11111111-1111-4111-8111-111111111111"), + ACCOUNT, + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 71L, + 73L, + 82L); + return new CanonicalGameplayRosterOwnerReadEvidence(request, "1".repeat(64), proof, set); + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof pendingProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity identity) { + return new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java new file mode 100644 index 0000000000..78c03f25e5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalInitialAdmissionOwnerProofCodecTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final Instant TERMINAL_AT = Instant.parse("2025-02-03T04:05:06.123456Z"); + + @Test + void literalClosedHoldVectorsRemainBoundToDistinctRequestAndWorldDigests() { + var identity = holdIdentity(InitialAdmissionOrigin.EXPECT_CLOSED, 13L); + + assertThat(identity.request().initialAdmissionRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(identity.holdBindingDigest()) + .isEqualTo("sha256:6905884b086d38cb14fc9886b1b7e8b125358d9c33dc23f0300c3c387a022b72"); + assertThat(identity.holdBindingDigest()).isNotEqualTo("sha256:" + REQUEST_DIGEST); + } + + @Test + void committedPendingAndAbortedResultsRoundTripAsDistinctClosedOutcomes() { + var identity = holdIdentity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.PENDING, null, null, null, false, null); + var committed = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.COMMITTED, 14L, 55L, "sha256:" + "b".repeat(64), false, TERMINAL_AT); + var aborted = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.ABORTED, null, null, "sha256:" + "c".repeat(64), true, TERMINAL_AT); + + for (var proof : + new GameSessionCanonicalInitialAdmissionOwnerProof[] {pending, committed, aborted}) { + byte[] bytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof); + assertThat(GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(bytes)) + .isEqualTo(proof); + } + assertThat(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(committed)) + .isNotEqualTo(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(aborted)); + } + + @Test + void everyTerminalBindingAndResultChangeChangesCanonicalOwnerProofBytes() { + var identity = holdIdentity(InitialAdmissionOrigin.EXPECT_CLOSED, 13L); + var base = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.COMMITTED, 14L, 55L, "sha256:" + "b".repeat(64), false, TERMINAL_AT); + byte[] bytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(base); + + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity(InitialAdmissionOrigin.EXPECT_CLOSED, 12L), + Outcome.COMMITTED, + 14L, + 55L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.COMMITTED, + 15L, + 55L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.COMMITTED, + 14L, + 56L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + assertThat( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.COMMITTED, + 14L, + 55L, + "sha256:" + "d".repeat(64), + false, + TERMINAL_AT))) + .isNotEqualTo(bytes); + } + + @Test + void rejectsAmbiguousOrContradictoryTerminalFields() { + var identity = holdIdentity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.PENDING, null, null, "sha256:" + "a".repeat(64), false, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.ABORTED, + 14L, + null, + "sha256:" + "a".repeat(64), + true, + TERMINAL_AT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.ABORTED, + null, + null, + "sha256:" + "a".repeat(64), + false, + TERMINAL_AT)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static HoldIdentity holdIdentity( + InitialAdmissionOrigin origin, Long priorPointerVersion) { + var request = + new Request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + origin, + 12L, + priorPointerVersion); + return new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java new file mode 100644 index 0000000000..e74be61eae --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java @@ -0,0 +1,198 @@ +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.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; +import org.junit.jupiter.api.Test; + +class PreseededActorAssignmentOwnerReadEvidenceTest { + private static final String TARGET_NAMESPACE = "gameplay"; + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REALM = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID PLAYABLE_NAMESPACE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID INSTANCE = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-08T03:04:05Z"); + + @Test + void assignmentRequestOmitsCountersAndResponseCarriesCountersOnlyFromOwnerProof() + throws Exception { + var evidence = fixture(); + var request = evidence.request(); + var wireRequest = PreseededActorAssignmentOwnerReadGrpcCodec.toRequest(request); + + assertThat(wireRequest.getAllFields().keySet()) + .noneMatch( + field -> field.getName().contains("pointer") || field.getName().contains("epoch")); + assertThat(PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + assertThat(evidence.sourceEvidence().request().expectedPointerVersion()).isEqualTo(73L); + assertThat(evidence.sourceEvidence().request().expectedActiveWorldEpoch()).isEqualTo(82L); + + var response = PreseededActorAssignmentOwnerReadGrpcCodec.toResponse(request, evidence); + assertThat(response.hasRequest()).isTrue(); + assertThat(response.getRequest()).isEqualTo(wireRequest); + assertThat(PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(evidence); + } + + @Test + void rejectsChangedSelectorsPolicyReleaseUnknownFieldsAndPartialSourceEvidence() + throws Exception { + var evidence = fixture(); + var request = evidence.request(); + var wireRequest = PreseededActorAssignmentOwnerReadGrpcCodec.toRequest(request); + var response = PreseededActorAssignmentOwnerReadGrpcCodec.toResponse(request, evidence); + + var changedDigest = + new PreseededActorAssignmentOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + "9".repeat(64), + request.expectedPublishedReleaseBundleRef()); + assertThatThrownBy( + () -> + new PreseededActorAssignmentOwnerReadEvidence( + changedDigest, evidence.sourceEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var changedRelease = + new PreseededActorAssignmentOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + request.expectedPolicyDigest(), + "substituted-release"); + assertThatThrownBy( + () -> + new PreseededActorAssignmentOwnerReadEvidence( + changedRelease, evidence.sourceEvidence())) + .isInstanceOf(IllegalArgumentException.class); + + var unknownRequest = + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy(() -> PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( + request, GetPreseededActorAssignmentOwnerReadResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wireRequest.toBuilder().setRealmSlug("other").build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static PreseededActorAssignmentOwnerReadEvidence fixture() throws Exception { + var policySet = PublishedRealmEntryPolicySetEvidenceTest.preseededSetFixture(); + var selectedPolicy = policySet.policies().getFirst(); + UUID tenant = policySet.target().canonicalTenantId(); + UUID version = policySet.target().canonicalVersionId(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + TERMINAL_AT); + var sourceRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("11111111-1111-4111-8111-111111111111"), + ACCOUNT, + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 71L, + 73L, + 82L); + var sourceEvidence = + new CanonicalGameplayRosterOwnerReadEvidence( + sourceRequest, "1".repeat(64), proof, policySet); + var request = + new PreseededActorAssignmentOwnerReadEvidence.Request( + sourceRequest.requestUuid(), + ACCOUNT, + TARGET_NAMESPACE, + tenant, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + version, + 71L, + raw(selectedPolicy.policyDigest()), + policySet.publishedReleaseBundleRef()); + return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); + } + + private static String raw(String digest) { + return digest.startsWith("sha256:") ? digest.substring("sha256:".length()) : digest; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java new file mode 100644 index 0000000000..0eebaa9333 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java @@ -0,0 +1,544 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +/** Closed wire and complete-set proof over isolated publication fixture vectors. */ +class PublishedRealmEntryPolicyReadGrpcCodecTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void listAndResolveRoundTripTheCompleteOrderedSealedSet() throws Exception { + Fixture fixture = fixture(true); + var listRequest = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + var resolveRequest = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); + + var listWire = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(listRequest); + var resolveWire = PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolveRequest); + assertThat(PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(listWire)).isEqualTo(listRequest); + assertThat(PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(resolveWire)) + .isEqualTo(resolveRequest); + + var listResponse = + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(listRequest, fixture.set()); + var resolveResponse = + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(resolveRequest, fixture.set()); + var listed = PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(listRequest, listResponse); + var resolved = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolveResponse); + + assertThat(listed).isEqualTo(fixture.set()); + assertThat(resolved).isEqualTo(fixture.set()); + assertThat(listed.policyCount()).isEqualTo(2); + assertThat(listed.policies()).containsExactlyElementsOf(fixture.set().policies()); + assertThat(listed.policySetDigest()).isEqualTo(fixture.set().policySetDigest()); + assertThat(listed.operationBytes()).isEqualTo(fixture.set().operationBytes()); + assertThat(listed.captureBytes()).isEqualTo(fixture.set().captureBytes()); + assertThat(listed.terminalEvidenceBytes()).isEqualTo(fixture.set().terminalEvidenceBytes()); + } + + @Test + void requestsRejectUnknownFieldsUnsupportedSchemaAndNoncanonicalIdentityOrSelectors() + throws Exception { + Fixture fixture = fixture(false); + var validList = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest( + listRequest(fixture, "99999999-9999-4999-8999-999999999999")); + var validResolve = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest( + resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main")); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder().setUnknownFields(unknown).build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setSchemaVersion(2).build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder() + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder() + .setCanonicalTenantId("BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB") + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder().setTargetNamespace("Test").build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setWorldSlug("Main").build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setRealmSlug("bad--slug").build())); + } + + @Test + void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { + Fixture fixture = fixture(false); + var request = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + var response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, fixture.set()); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setTargetNamespace("other")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("88888888-8888-4888-8888-888888888888")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setCanonicalTenantId("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setCanonicalVersionId("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")) + .build())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())); + + var wrongTarget = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + request.targetNamespace(), + request.readRequestId(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request.canonicalVersionId()); + var substitutedEvidence = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(wrongTarget)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + wrongTarget, substitutedEvidence)); + + var resolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "missing"); + var missingSelectorResponse = + ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(resolve)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + resolve, missingSelectorResponse)); + + var exactResolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); + var exactResolveResponse = + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(exactResolve, fixture.set()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + exactResolve, + exactResolveResponse.toBuilder() + .setRequest( + exactResolveResponse.getRequest().toBuilder().setRealmSlug("side")) + .build())); + } + + @Test + void completeCarrierRejectsCountOrderAndDigestSubstitutionAtTheWireBoundary() throws Exception { + Fixture fixture = fixture(true); + var request = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + byte[] canonical = fixture.set().canonicalBytes(); + ObjectNode root = (ObjectNode) JSON.readTree(canonical); + + ObjectNode changedCount = root.deepCopy(); + changedCount.put("policyCount", fixture.set().policyCount() + 1); + assertRejectedSet(request, changedCount); + + ObjectNode changedOrder = root.deepCopy(); + ArrayNode reversed = JSON.createArrayNode(); + ArrayNode policies = (ArrayNode) changedOrder.get("policies"); + for (int index = policies.size() - 1; index >= 0; index--) { + reversed.add(policies.get(index)); + } + changedOrder.set("policies", reversed); + assertRejectedSet(request, changedOrder); + + ObjectNode changedDigest = root.deepCopy(); + changedDigest.put("policySetDigest", "sha256:" + "f".repeat(64)); + assertRejectedSet(request, changedDigest); + } + + private static void assertRejectedSet( + PublishedRealmEntryPolicyReadGrpcCodec.ListRequest request, ObjectNode carrier) + throws IOException { + byte[] changed = Rfc8785CanonicalJson.canonicalizeUtf8(carrier.toString()); + var response = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(request)) + .setPolicySetEvidence(ByteString.copyFrom(changed)) + .build(); + assertThatIllegalArgumentException() + .isThrownBy(() -> PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(request, response)); + } + + private static PublishedRealmEntryPolicyReadGrpcCodec.ListRequest listRequest( + Fixture fixture, String readId) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + "test", + UUID.fromString(readId), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + } + + private static PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest resolveRequest( + Fixture fixture, String readId, String realmSlug) { + return new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + "test", + UUID.fromString(readId), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + "earth", + realmSlug); + } + + private static Fixture fixture(boolean includeSide) throws Exception { + var operation = operation(); + var target = operation.account().input().selection().target(); + var sourceBinding = operation.account().input().selection().selectedCommit(); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, release(operation), 6L); + List sources = new ArrayList<>(); + sources.add( + source( + "main", + true, + "33333333-3333-4333-8333-333333333333", + "44444444-4444-4444-8444-444444444444", + "55555555-5555-4555-8555-555555555555")); + if (includeSide) { + sources.add( + source( + "side", + false, + "88888888-8888-4888-8888-888888888888", + "66666666-6666-4666-8666-666666666666", + "77777777-7777-4777-8777-777777777777")); + } + byte[] capture = capture(operation, sourceBinding, sources); + List policies = + sources.stream() + .map( + source -> { + UUID policyId = UUID.fromString(source.policyId()); + return new PublishedRealmEntryPolicyEvidence( + policyId, + UUID.fromString(source.commitId()), + UUID.fromString(source.revisionId()), + "source-" + source.revisionId(), + source.policy(), + PublishedRealmEntryPolicySetEvidence.policyDigest( + policyId, + target, + terminal.releaseContent().versionNumber(), + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + UUID.fromString(source.commitId()), + UUID.fromString(source.revisionId()), + "source-" + source.revisionId(), + source.policy())); + }) + .toList(); + var release = terminal.releaseContent(); + String setDigest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + release.versionNumber(), + sourceBinding.commitId(), + "43", + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + return new Fixture( + target, + new PublishedRealmEntryPolicySetEvidence( + target, + release.versionNumber(), + sourceBinding.commitId(), + "43", + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies.size(), + setDigest, + policies)); + } + + private static Source source( + String realm, boolean production, String policyId, String commitId, String revisionId) { + RealmEntryPolicy policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"" + + realm + + "\",\"visible\":true,\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON); + return new Source(policyId, commitId, revisionId, policy); + } + + private static byte[] capture( + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding operation, + DraftCommitBinding binding, + List sources) + throws IOException { + List> policies = + sources.stream() + .map( + source -> { + Map value = new LinkedHashMap<>(); + value.put("commitId", source.commitId()); + value.put("revisionId", source.revisionId()); + value.put("logicalRevisionId", "source-" + source.revisionId()); + value.put("policy", JSON.readTree(source.policy().canonicalJson())); + return value; + }) + .toList(); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "43"); + snapshot.put("policies", policies); + byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } + + private static net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding + operation() throws Exception { + var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String requestId = "publication-request"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + "5", + "fixed-notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var request = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + requestId, + selected.digest().substring(7), + 5L, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + requestId) + .derivedWorkflowIdentity(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperationBinding(account, world); + } + + private static ReleaseContent release( + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding operation) { + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + 12, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-é"), + participants, + List.of("LOOK"), + "generation-1", + operation.world()); + } + + private record Source( + String policyId, String commitId, String revisionId, RealmEntryPolicy policy) {} + + private record Fixture( + DraftCommitBinding.TargetProof target, PublishedRealmEntryPolicySetEvidence set) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java new file mode 100644 index 0000000000..8c4be9e883 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -0,0 +1,636 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Fixed isolated fixtures prove carrier integrity, not owner producer, database, or mTLS proof. */ +class PublishedRealmEntryPolicySetEvidenceTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final ObjectMapper JSON = new ObjectMapper(); + + static PublishedRealmEntryPolicySetEvidence preseededSetFixture() throws Exception { + return fixture(false).set(); + } + + @Test + void completeSetRetainsTheActualOperationCaptureTerminalAndOrderedSourceRows() throws Exception { + Fixture fixture = fixture(false); + var restored = PublishedRealmEntryPolicySetEvidence.fromStored(fixture.set().canonicalBytes()); + + assertThat(fixture.set().hasValidDigest()).isTrue(); + assertThat(restored).isEqualTo(fixture.set()); + assertThat(restored.canonicalBytes()).isEqualTo(fixture.set().canonicalBytes()); + assertThat(restored.target()).isEqualTo(fixture.target()); + assertThat(restored.sourceCommitId()).isEqualTo(fixture.sourceBinding().commitId()); + assertThat(restored.sourceEpoch()).isEqualTo("43"); + assertThat(restored.policyCount()).isEqualTo(1); + assertThat(restored.policies()).containsExactlyElementsOf(fixture.policies()); + assertThat(restored.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + assertThat(restored.captureBytes()).isEqualTo(fixture.captureBytes()); + assertThat(restored.terminalEvidenceBytes()).isEqualTo(fixture.terminal().canonicalBytes()); + } + + @Test + void completeSetRejectsCountMissingOrderDuplicateAndDigestChanges() throws Exception { + Fixture fixture = fixture(true); + var set = fixture.set(); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> copy(fixture, set.policyCount() + 1, set.policies(), set.policySetDigest())); + assertThatIllegalArgumentException() + .isThrownBy(() -> copy(fixture, 0, List.of(), set.policySetDigest())); + var reversed = new ArrayList<>(set.policies()); + java.util.Collections.reverse(reversed); + assertThat( + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + reversed)) + .isEqualTo(set.policySetDigest()); + assertThatIllegalArgumentException() + .isThrownBy(() -> copy(fixture, reversed.size(), reversed, set.policySetDigest())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> copy(fixture, set.policyCount(), set.policies(), "sha256:" + "f".repeat(64))); + var invalidChildDigest = + new PublishedRealmEntryPolicyEvidence( + fixture.policies().getFirst().policyId(), + fixture.policies().getFirst().sourceCommitId(), + fixture.policies().getFirst().sourceRevisionId(), + fixture.policies().getFirst().logicalRevisionId(), + fixture.policies().getFirst().policy(), + "sha256:" + "f".repeat(64)); + var invalidChildren = List.of(invalidChildDigest, set.policies().getLast()); + var digestOverInvalidChild = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + invalidChildren); + assertThatIllegalArgumentException() + .isThrownBy( + () -> copy(fixture, set.policyCount(), invalidChildren, digestOverInvalidChild)); + + var duplicateSource = + List.of( + fixture.policies().getFirst(), + new PublishedRealmEntryPolicyEvidence( + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + "duplicate-realm-in-another-world", + policy("mars", "Mars", "main", "Main", false, false), + DIGEST)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + fixture.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + duplicateSource)); + } + + @Test + void completeSetRejectsChildSourceScopeCaptureTerminalAndBundleSubstitution() throws Exception { + Fixture fixture = fixture(false); + var set = fixture.set(); + var original = fixture.policies().getFirst(); + var changedSource = + new PublishedRealmEntryPolicyEvidence( + original.policyId(), + original.sourceCommitId(), + uuid("99999999-9999-4999-8999-999999999999"), + original.logicalRevisionId(), + original.policy(), + original.policyDigest()); + assertThatIllegalArgumentException() + .isThrownBy(() -> copy(fixture, 1, List.of(changedSource), set.policySetDigest())); + + var changedTarget = + new DraftCommitBinding.TargetProof( + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.target().gameDesignVersionRowId() + 1, + fixture.target().gameDesignVersionTenantKey(), + fixture.target().sourceGameRowId(), + fixture.target().sourceGameTenantKey(), + fixture.target().sourceProvenanceKind()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + changedTarget, + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + var changedOperation = operation(6L); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + changedOperation.canonicalBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + byte[] substitutedCapture = + capture(fixture.operation(), fixture.sourceBinding(), "44", fixture.sources()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + substitutedCapture, + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + var substitutedTerminal = terminal(fixture.operation(), fixture.release("generation-2"), 6L); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + substitutedTerminal.canonicalBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + "substituted-bundle-reference", + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); + } + + @Test + void storedSetRejectsUnknownAndNoncanonicalCarrierBytes() throws Exception { + Fixture fixture = fixture(false); + byte[] spaced = (" " + fixture.set().canonicalJson()).getBytes(StandardCharsets.UTF_8); + assertThatIllegalArgumentException() + .isThrownBy(() -> PublishedRealmEntryPolicySetEvidence.fromStored(spaced)); + + ObjectNode withUnknown = (ObjectNode) JSON.readTree(fixture.set().canonicalJson()); + withUnknown.put("unrecognized", "field"); + byte[] unknown = Rfc8785CanonicalJson.canonicalizeUtf8(withUnknown.toString()); + assertThatIllegalArgumentException() + .isThrownBy(() -> PublishedRealmEntryPolicySetEvidence.fromStored(unknown)); + } + + private static PublishedRealmEntryPolicySetEvidence copy( + Fixture fixture, + int policyCount, + List policies, + String digest) { + var set = fixture.set(); + return new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + policyCount, + digest, + policies); + } + + private static Fixture fixture(boolean includeSide) throws Exception { + GameDesignPublicationOperationBinding operation = operation(5L); + var target = operation.account().input().selection().target(); + var sourceBinding = operation.account().input().selection().selectedCommit(); + var terminal = terminal(operation, release(operation, "generation-1"), 6L); + List sources = new ArrayList<>(); + sources.add( + source( + "earth", + "Earth", + "main", + "Main", + true, + true, + "33333333-3333-4333-8333-333333333333", + "44444444-4444-4444-8444-444444444444", + "55555555-5555-4555-8555-555555555555", + "main-policy-v1")); + if (includeSide) { + sources.add( + source( + "earth", + "Earth", + "side", + "Side", + true, + false, + "88888888-8888-4888-8888-888888888888", + "66666666-6666-4666-8666-666666666666", + "77777777-7777-4777-8777-777777777777", + "side-policy-v1")); + } + byte[] capture = capture(operation, sourceBinding, "43", sources); + List policies = + sources.stream() + .map( + source -> { + UUID policyId = UUID.fromString(source.policyId()); + String policyDigest = + PublishedRealmEntryPolicySetEvidence.policyDigest( + policyId, + target, + terminal.releaseContent().versionNumber(), + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + UUID.fromString(source.sourceCommitId()), + UUID.fromString(source.sourceRevisionId()), + source.logicalRevisionId(), + source.policy()); + return new PublishedRealmEntryPolicyEvidence( + policyId, + UUID.fromString(source.sourceCommitId()), + UUID.fromString(source.sourceRevisionId()), + source.logicalRevisionId(), + source.policy(), + policyDigest); + }) + .toList(); + var setDigest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + terminal.releaseContent().versionNumber(), + sourceBinding.commitId(), + "43", + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + var set = + new PublishedRealmEntryPolicySetEvidence( + target, + terminal.releaseContent().versionNumber(), + sourceBinding.commitId(), + "43", + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies.size(), + setDigest, + policies); + return new Fixture( + target, operation, sourceBinding, terminal, capture, List.copyOf(sources), policies, set); + } + + private static Source source( + String world, + String worldName, + String realm, + String realmName, + boolean visible, + boolean production, + String policyId, + String sourceCommitId, + String sourceRevisionId, + String logicalRevisionId) { + return new Source( + policyId, + sourceCommitId, + sourceRevisionId, + logicalRevisionId, + policy(world, worldName, realm, realmName, visible, production)); + } + + private static RealmEntryPolicy policy( + String world, + String worldName, + String realm, + String realmName, + boolean visible, + boolean production) { + return RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"" + + world + + "\",\"worldDisplayName\":\"" + + worldName + + "\",\"realmSlug\":\"" + + realm + + "\",\"realmDisplayName\":\"" + + realmName + + "\",\"visible\":" + + visible + + ",\"publicProduction\":" + + production + + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON); + } + + private static byte[] capture( + GameDesignPublicationOperationBinding operation, + DraftCommitBinding binding, + String sourceEpoch, + List sources) + throws IOException { + List> policies = + sources.stream() + .map( + source -> { + Map value = new LinkedHashMap<>(); + value.put("commitId", source.sourceCommitId()); + value.put("revisionId", source.sourceRevisionId()); + value.put("logicalRevisionId", source.logicalRevisionId()); + value.put("policy", JSON.readTree(source.policy().canonicalJson())); + return value; + }) + .toList(); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", sourceEpoch); + snapshot.put("policies", policies); + byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } + + private static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, ReleaseContent release, long epoch) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, release, epoch); + } + + private static ReleaseContent release( + GameDesignPublicationOperationBinding operation, String generation) { + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + 12, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-é"), + participants, + List.of("LOOK"), + generation, + operation.world()); + } + + private static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { + var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String request = "publication-request"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request, + Long.toString(epoch), + "fixed-notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var requestEvidence = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + requestEvidence.targetNamespace(), + requestEvidence.canonicalTenantId(), + requestEvidence.canonicalVersionId(), + requestEvidence.intakeRequestId(), + requestEvidence.publicationFence(), + request, + selected.digest().substring(7), + epoch, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + request) + .derivedWorkflowIdentity(), + requestEvidence.appliedCommitId(), + requestEvidence.contentDigest(), + requestEvidence.digestSchemaVersion(), + requestEvidence.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperationBinding(account, world); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Source( + String policyId, + String sourceCommitId, + String sourceRevisionId, + String logicalRevisionId, + RealmEntryPolicy policy) {} + + private record Fixture( + DraftCommitBinding.TargetProof target, + GameDesignPublicationOperationBinding operation, + DraftCommitBinding sourceBinding, + GameDesignPublicationTerminalEvidence terminal, + byte[] captureBytes, + List sources, + List policies, + PublishedRealmEntryPolicySetEvidence set) { + private ReleaseContent release(String generation) { + return PublishedRealmEntryPolicySetEvidenceTest.release(operation, generation); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java new file mode 100644 index 0000000000..1ec288c5fa --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java @@ -0,0 +1,596 @@ +package unit.net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInitialAdmissionHoldTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID OTHER_UUID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String OTHER_REQUEST_DIGEST = "b".repeat(64); + private static final String NO_PRIOR_VECTOR = + "{\"request\":{\"activeLifecycleEpoch\":\"7\",\"canonicalGameInstanceId\":\"44444444-4444-4444-8444-444444444444\",\"canonicalTenantId\":\"11111111-1111-4111-8111-111111111111\",\"canonicalVersionId\":\"55555555-5555-4555-8555-555555555555\",\"expectedCatalogRevision\":\"12\",\"expectedPriorPointerVersion\":null,\"initialAdmissionOrigin\":\"NO_PRIOR_POINTER\",\"initialAdmissionRequestDigest\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"initialAdmissionRequestId\":\"gs-initial-admission-17\",\"playableStateNamespaceId\":\"33333333-3333-4333-8333-333333333333\",\"playableStateScope\":\"SHARED\",\"realmId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"prod\",\"worldSlug\":\"green-hollow\"},\"schema\":\"world-canonical-initial-admission-hold-request/v1\"}"; + private static final String EXPECT_CLOSED_VECTOR = + "{\"request\":{\"activeLifecycleEpoch\":\"7\",\"canonicalGameInstanceId\":\"44444444-4444-4444-8444-444444444444\",\"canonicalTenantId\":\"11111111-1111-4111-8111-111111111111\",\"canonicalVersionId\":\"55555555-5555-4555-8555-555555555555\",\"expectedCatalogRevision\":\"12\",\"expectedPriorPointerVersion\":\"13\",\"initialAdmissionOrigin\":\"EXPECT_CLOSED\",\"initialAdmissionRequestDigest\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"initialAdmissionRequestId\":\"gs-initial-admission-17\",\"playableStateNamespaceId\":\"33333333-3333-4333-8333-333333333333\",\"playableStateScope\":\"SHARED\",\"realmId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"prod\",\"worldSlug\":\"green-hollow\"},\"schema\":\"world-canonical-initial-admission-hold-request/v1\"}"; + + @Test + void emitsLiteralCanonicalVectorsForBothApprovedOrigins() { + Request noPrior = noPriorRequest(); + Request expectClosed = expectClosedRequest(13L); + + assertThat(utf8(noPrior.canonicalRequestBytes())).isEqualTo(NO_PRIOR_VECTOR); + assertThat(utf8(expectClosed.canonicalRequestBytes())).isEqualTo(EXPECT_CLOSED_VECTOR); + assertThat(noPrior.holdBindingDigest()) + .isEqualTo("sha256:c6add7b8085af587261e3f41a01568e2a02f66b3f5ae3c4852dbc5124421f10a"); + assertThat(expectClosed.holdBindingDigest()) + .isEqualTo("sha256:6905884b086d38cb14fc9886b1b7e8b125358d9c33dc23f0300c3c387a022b72"); + assertThat(noPrior.initialAdmissionRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(noPrior.holdBindingDigest()) + .isNotEqualTo("sha256:" + noPrior.initialAdmissionRequestDigest()); + } + + @Test + void requestAndAcquiredIdentityRoundTripAndExactRetryKeepTheirCanonicalIdentity() { + Request noPrior = noPriorRequest(); + Request request = expectClosedRequest(13L); + Request decodedNoPrior = Request.fromStored(noPrior.canonicalRequestBytes()); + Request decodedRequest = Request.fromStored(request.canonicalRequestBytes()); + HoldIdentity acquired = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + HoldIdentity decoded = HoldIdentity.fromStored(acquired.canonicalBytes()); + HoldIdentity exactRetry = new HoldIdentity(decodedRequest, HOLD_ID, HOLD_FENCE); + + assertThat(decodedNoPrior).isEqualTo(noPrior); + assertThat(decodedRequest).isEqualTo(request); + assertThat(decoded).isEqualTo(acquired); + assertThat(decoded.canonicalBytes()).containsExactly(acquired.canonicalBytes()); + assertThat(exactRetry.canonicalBytes()).containsExactly(acquired.canonicalBytes()); + assertThat(decoded.holdId()).isEqualTo(HOLD_ID); + assertThat(decoded.holdFence()).isEqualTo(HOLD_FENCE); + assertThat(decoded.holdBindingDigest()).isEqualTo(request.holdBindingDigest()); + } + + @Test + void everySupportedRequestFieldChangesTheCanonicalHoldBinding() { + Request base = noPriorRequest(); + assertBindingDiffers( + base, + request( + "staging", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + OTHER_UUID, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "blue-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + OTHER_UUID, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + OTHER_UUID, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + OTHER_UUID, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + OTHER_UUID, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 8L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-18", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + OTHER_REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)); + assertBindingDiffers(base, expectClosedRequest(13L)); + assertBindingDiffers(expectClosedRequest(13L), expectClosedRequest(14L)); + assertBindingDiffers( + base, + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 14L, + null)); + } + + @Test + void rejectsNilNoncanonicalAndInvalidScopeOrOriginInputs() { + assertThatThrownBy( + () -> + request( + "prod", + NIL_UUID, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null, + "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> Request.fromStored(utf8Bytes(NO_PRIOR_VECTOR.replace("SHARED", "ISOLATED")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> + Request.fromStored( + utf8Bytes(NO_PRIOR_VECTOR.replace("NO_PRIOR_POINTER", "FIRST_OPEN")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("initialAdmissionOrigin"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("NO_PRIOR_POINTER"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.EXPECT_CLOSED, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "A".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + " ", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonempty"); + assertThatThrownBy( + () -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "r".repeat(129), + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded"); + assertThatThrownBy(() -> new HoldIdentity(noPriorRequest(), NIL_UUID, HOLD_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("holdId"); + assertThatThrownBy(() -> new HoldIdentity(noPriorRequest(), HOLD_ID, NIL_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("holdFence"); + } + + @Test + void parserRejectsInvalidUuidsOptionalRepresentationsCountersAliasesAndUnknownInput() { + assertInvalidRequest(NO_PRIOR_VECTOR.replace(TENANT.toString(), NIL_UUID.toString())); + UUID alphaTenant = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); + String alphaTenantVector = utf8(noPriorRequestWithTenant(alphaTenant).canonicalRequestBytes()); + assertInvalidRequest( + alphaTenantVector.replace(alphaTenant.toString(), alphaTenant.toString().toUpperCase())); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"expectedPriorPointerVersion\":null", "\"expectedPriorPointerVersion\":\"1\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"initialAdmissionOrigin\":\"NO_PRIOR_POINTER\"", + "\"initialAdmissionOrigin\":\"EXPECT_CLOSED\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"expectedPriorPointerVersion\":null", "\"expectedPriorPointerVersion\":1")); + assertInvalidRequest(NO_PRIOR_VECTOR.replace(",\"expectedPriorPointerVersion\":null", "")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace("\"canonicalGameInstanceId\"", "\"gameInstanceId\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"worldSlug\":", "\"worldSlug\":\"green-hollow\",\"worldSlugAlias\":")); + assertInvalidRequest(NO_PRIOR_VECTOR + "{}"); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace(",\"worldSlug\":", ",\"targetNamespace\":\"prod\",\"worldSlug\":")); + + for (String value : new String[] {"0", "-1", "01", "9223372036854775808"}) { + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"activeLifecycleEpoch\":\"7\"", "\"activeLifecycleEpoch\":\"" + value + "\"")); + assertInvalidRequest( + NO_PRIOR_VECTOR.replace( + "\"expectedCatalogRevision\":\"12\"", + "\"expectedCatalogRevision\":\"" + value + "\"")); + assertInvalidRequest( + EXPECT_CLOSED_VECTOR.replace( + "\"expectedPriorPointerVersion\":\"13\"", + "\"expectedPriorPointerVersion\":\"" + value + "\"")); + } + assertInvalidRequest( + NO_PRIOR_VECTOR.replace("\"activeLifecycleEpoch\":\"7\"", "\"activeLifecycleEpoch\":7")); + + String identity = + utf8(new HoldIdentity(noPriorRequest(), HOLD_ID, HOLD_FENCE).canonicalBytes()); + assertThatThrownBy( + () -> + HoldIdentity.fromStored( + utf8Bytes( + identity.replace( + "\"holdBindingDigest\":\"" + noPriorRequest().holdBindingDigest(), + "\"holdBindingDigest\":\"sha256:" + "0".repeat(64))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + HoldIdentity.fromStored( + utf8Bytes( + identity.replace( + "\"holdId\":", + "\"legacyHoldId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\",\"holdId\":")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("closed object shape"); + } + + private static Request noPriorRequest() { + return request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static Request expectClosedRequest(long expectedPriorPointerVersion) { + return request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.EXPECT_CLOSED, + 12L, + expectedPriorPointerVersion); + } + + private static Request noPriorRequestWithTenant(UUID tenant) { + return request( + "prod", + tenant, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static Request request( + String namespace, + UUID tenant, + String slug, + UUID realm, + UUID playableNamespace, + UUID gameInstance, + UUID version, + long epoch, + String requestId, + String requestDigest, + InitialAdmissionOrigin origin, + long catalogRevision, + Long priorPointerVersion) { + return request( + namespace, + tenant, + slug, + realm, + playableNamespace, + gameInstance, + version, + epoch, + requestId, + requestDigest, + origin, + catalogRevision, + priorPointerVersion, + "SHARED"); + } + + private static Request request( + String namespace, + UUID tenant, + String slug, + UUID realm, + UUID playableNamespace, + UUID gameInstance, + UUID version, + long epoch, + String requestId, + String requestDigest, + InitialAdmissionOrigin origin, + long catalogRevision, + Long priorPointerVersion, + String scope) { + return new Request( + namespace, + tenant, + slug, + realm, + playableNamespace, + scope, + gameInstance, + version, + epoch, + requestId, + requestDigest, + origin, + catalogRevision, + priorPointerVersion); + } + + private static void assertBindingDiffers(Request original, Request changed) { + assertThat(changed.canonicalRequestBytes()).isNotEqualTo(original.canonicalRequestBytes()); + assertThat(changed.holdBindingDigest()).isNotEqualTo(original.holdBindingDigest()); + } + + private static void assertInvalidRequest(String json) { + assertThatThrownBy(() -> Request.fromStored(utf8Bytes(json))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static String utf8(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + private static byte[] utf8Bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java new file mode 100644 index 0000000000..9534727da0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class WorldDraftStartLocationEvidenceTest { + private static final String ACCOUNT_BINDING_DIGEST = "sha256:" + "0".repeat(64); + private static final String BINDING_DIGEST = "sha256:" + "1".repeat(64); + private static final String GRAPH_DIGEST = "sha256:" + "2".repeat(64); + private static final String RECEIPT_DIGEST = + "sha256:9f267c68a4915e5c28dd66536663783808210422fef4ae6062a8cd185d90636c"; + 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 RoomTemplateRef START_LOCATION = + new RoomTemplateRef( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + uuid("77777777-7777-4777-8777-777777777777")); + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + + @Test + void createMatchesTheOriginalReceiptPreimageAndCanonicalBytes() { + var evidence = evidence(); + + assertThat(evidence.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"accountBindingDigest\":\"sha256:" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "\",\"authorizationFenceId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"" + + ",\"bindingDigest\":\"sha256:" + + "1111111111111111111111111111111111111111111111111111111111111111" + + "\",\"commitId\":\"55555555-5555-4555-8555-555555555555\"" + + ",\"graphDigest\":\"sha256:" + + "2222222222222222222222222222222222222222222222222222222222222222" + + "\",\"operationId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"" + + ",\"receiptDigest\":\"sha256:" + + "9f267c68a4915e5c28dd66536663783808210422fef4ae6062a8cd185d90636c" + + "\",\"requestId\":\"44444444-4444-4444-8444-444444444444\"" + + ",\"schema\":\"world-draft-start-location-receipt/v1\"" + + ",\"startLocation\":{\"roomTemplateId\":\"77777777-7777-4777-8777-777777777777\"" + + ",\"tenantId\":\"11111111-1111-4111-8111-111111111111\"" + + ",\"versionId\":\"22222222-2222-4222-8222-222222222222\"}" + + ",\"targetNamespace\":\"test\"}"); + assertThat(WorldDraftStartLocationEvidence.fromStored(evidence.canonicalBytes())) + .isEqualTo(evidence); + } + + @Test + void fromStoredRejectsUnknownDuplicateTrailingInvalidUtf8AndNoncanonicalBytes() throws Exception { + byte[] canonical = evidence().canonicalBytes(); + String json = new String(canonical, StandardCharsets.UTF_8); + assertRejected((" " + json).getBytes(StandardCharsets.UTF_8)); + assertRejected((json + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected( + (json.substring(0, json.length() - 1) + ",\"unsupported\":true}") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace("\"startLocation\":{", "\"startLocation\":{\"unsupported\":true,") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace( + "\"targetNamespace\":\"test\"", + "\"targetNamespace\":\"test\",\"targetNamespace\":\"test\"") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace( + "\"startLocation\":{", + "\"startLocation\":{\"tenantId\":\"11111111-1111-4111-8111-111111111111\",") + .getBytes(StandardCharsets.UTF_8)); + byte[] invalidUtf8 = canonical.clone(); + invalidUtf8[1] = (byte) 0xc3; + assertRejected(invalidUtf8); + } + + @Test + void fromStoredRejectsNilNoncanonicalAndDigestSubstitutedFields() throws Exception { + for (Consumer change : + List.>of( + receipt -> receipt.put("schema", "world-draft-start-location-receipt/v2"), + receipt -> receipt.put("operationId", "00000000-0000-0000-0000-000000000000"), + receipt -> receipt.put("operationId", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA"), + receipt -> receipt.put("targetNamespace", "test-two"), + receipt -> receipt.put("operationId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("requestId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("commitId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("authorizationFenceId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("accountBindingDigest", "sha256:" + "f".repeat(64)), + receipt -> receipt.put("bindingDigest", "sha256:" + "f".repeat(64)), + receipt -> selector(receipt).put("tenantId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> selector(receipt).put("versionId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> + selector(receipt).put("roomTemplateId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("graphDigest", "sha256:" + "f".repeat(64)), + receipt -> receipt.put("receiptDigest", "sha256:" + "f".repeat(64)))) { + assertRejected(changed(change)); + } + + assertThatThrownBy( + () -> + WorldDraftStartLocationEvidence.create( + "invalid/namespace", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldDraftStartLocationEvidence evidence() { + return WorldDraftStartLocationEvidence.create( + "test", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST); + } + + private static byte[] changed(Consumer change) throws Exception { + ObjectNode receipt = (ObjectNode) JSON.readTree(evidence().canonicalBytes()); + change.accept(receipt); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(receipt)); + } + + private static ObjectNode selector(ObjectNode receipt) { + return (ObjectNode) receipt.get("startLocation"); + } + + private static void assertRejected(byte[] stored) { + assertThatThrownBy(() -> WorldDraftStartLocationEvidence.fromStored(stored)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java new file mode 100644 index 0000000000..58a6606492 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -0,0 +1,179 @@ +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.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedStartLocationGrpcCodecTest { + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + @Test + void exactSelectionAndRetainedEvidenceRoundTripAcrossReadRetries() throws Exception { + WorldPublishedStartLocationEvidence expected = evidence(); + var wireRequest = WorldPublishedStartLocationGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedStartLocationGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(expected.request()); + + var firstResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + var retryResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var first = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), firstResponse); + var retry = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), retryResponse); + assertThat(first.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(retry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat( + WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()).canonicalBytes()) + .containsExactly(first.canonicalBytes()); + var decoded = WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()); + assertThat(decoded).isEqualTo(expected); + assertThat(decoded.hashCode()).isEqualTo(expected.hashCode()); + } + + @Test + void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws Exception { + WorldPublishedStartLocationEvidence evidence = evidence(); + ReadWorldPublishedStartLocationResponse response = + WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setPublicationFence( + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact selection"); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setSelectorReceiptBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setOriginalAccountBindingBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setAppliedResultBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + evidence.request(), + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + + var changedIntake = + new WorldPublishedStartLocationEvidence.Request( + evidence.request().targetNamespace(), + evidence.request().canonicalTenantId(), + evidence.request().canonicalVersionId(), + uuid("99999999-9999-4999-8999-999999999999"), + evidence.request().publicationFence(), + evidence.request().publicationRequestId(), + evidence.request().requestDigest(), + evidence.request().versionStateEpoch(), + evidence.request().publishWorkflowId(), + evidence.request().appliedCommitId(), + evidence.request().contentDigest(), + evidence.request().digestSchemaVersion(), + evidence.request().worldAffectedTuples()); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + changedIntake, + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + evidence.appliedResultBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intake request"); + } + + static WorldPublishedStartLocationEvidence evidence() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = freshGraphReadback(terminalRequest); + 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 WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + return WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + } + + private static OwnerReadback freshGraphReadback(WorldDraftTerminalReadEvidence.Request request) + throws Exception { + return WorldDraftTerminalReadGrpcCodecTest + .committedFreshGraphReadbackForStartLocationEvidenceTest(request); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java new file mode 100644 index 0000000000..de3e7b5d75 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java @@ -0,0 +1,224 @@ +package unit.net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +class DraftCommitBindingTest { + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Test + void canonicalBindingRetainsCompleteOpaqueInputsAndDecimalCounters() { + DraftCommitBinding binding = binding(); + DraftCommitBinding restored = + DraftCommitBinding.fromStored(binding.canonicalJson(), binding.digest()); + + assertThat(restored).isEqualTo(binding); + assertThat(binding.canonicalJson()) + .contains("\"gameDesignVersionRowId\":\"9007199254740993\"") + .contains("\"sourceGameRowId\":\"9007199254740995\"") + .contains("\"expectedEpoch\":\"" + LARGE_EPOCH + "\"") + .contains("unknownTypedField") + .contains("\\n \\\"full\\\": true"); + assertThat(binding.requiredOwners()) + .containsExactly(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(binding.affectedUnits()) + .extracting(AffectedUnit::aggregateType, AffectedUnit::aggregateId) + .containsExactly( + org.assertj.core.groups.Tuple.tuple("WORLD_TEMPLATE", "world-23"), + org.assertj.core.groups.Tuple.tuple("ENTITY_TEMPLATE", "entity-17")); + + byte[] firstRead = binding.canonicalBytes(); + firstRead[0] = (byte) (firstRead[0] ^ 1); + assertThat(binding.canonicalBytes()).isNotEqualTo(firstRead); + assertThat(new String(binding.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo(binding.canonicalJson()); + } + + @Test + void canonicalBindingIsStableAcrossAffectedInputOrder() { + DraftCommitBinding first = binding(); + DraftCommitBinding reordered = + DraftCommitBinding.create( + first.target(), + first.requestId(), + first.commitId(), + first.baseCommitId(), + first.revisions(), + List.of(first.affectedUnits().get(1), first.affectedUnits().get(0))); + + assertThat(reordered.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(reordered.digest()).isEqualTo(first.digest()); + } + + @Test + void collectionAccessorsReturnImmutableCopies() { + DraftCommitBinding binding = binding(); + + assertThatThrownBy(() -> binding.revisions().add(binding.revisions().getFirst())) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.affectedUnits().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> binding.requiredOwners().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsMissingOrNonArrayStoredCollections() { + DraftCommitBinding original = binding(); + ObjectMapper json = new ObjectMapper(); + + ObjectNode missingRevisions = (ObjectNode) json.readTree(original.canonicalJson()); + missingRevisions.remove("revisions"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(missingRevisions), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + + ObjectNode invalidAffectedUnits = (ObjectNode) json.readTree(original.canonicalJson()); + invalidAffectedUnits.put("affectedUnits", "not-an-array"); + assertThatThrownBy( + () -> + DraftCommitBinding.fromStored( + json.writeValueAsString(invalidAffectedUnits), original.digest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + } + + @Test + void rejectsOmittedDuplicateOrInconsistentCanonicalOrder() { + DraftCommitBinding original = binding(); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner set"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0), original.revisions().get(0)), + original.affectedUnits())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical array order"); + assertThatThrownBy( + () -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + original.revisions(), + List.of(original.affectedUnits().get(0), original.affectedUnits().get(0)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate affected"); + } + + @Test + void rejectsNonCanonicalCountersAndNilOrUnprovedTargetIdentity() { + DraftCommitBinding original = binding(); + AffectedUnit affected = original.affectedUnits().getFirst(); + assertThatThrownBy( + () -> + new AffectedUnit( + affected.owner(), + affected.aggregateType(), + affected.aggregateId(), + affected.scopeType(), + affected.scopeId(), + "01")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + assertThatThrownBy( + () -> + new TargetProof( + new UUID(0L, 0L), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "tenant-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + new TargetProof( + original.target().canonicalTenantId(), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "different-source", + "NEW_GAME_ROW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must match exactly"); + } + + private DraftCommitBinding binding() { + return DraftCommitBinding.create( + new TargetProof( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 9_007_199_254_740_993L, + "tenant-source", + 9_007_199_254_740_995L, + "tenant-source", + "NEW_GAME_ROW"), + uuid("33333333-3333-4333-8333-333333333333"), + uuid("44444444-4444-4444-8444-444444444444"), + "base-commit-opaque-01", + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.WORLD_MANAGEMENT, + "{\n \"full\": true, \"unknownTypedField\": {\"keep\": \"all\"}\n}"), + new RevisionPayload( + "1", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.ENTITY_MANAGEMENT, + "{\"actorTemplate\":{\"complete\":true}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-23", + "ROOM_SCOPE", + "room-scope-3", + LARGE_EPOCH), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-17", + "ACTOR_SCOPE", + "actor-scope-2", + "0"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java deleted file mode 100644 index 564ea95722..0000000000 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.firedevops.firemud.entitymanagement.entity; - -import java.util.Objects; -import java.util.UUID; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import org.springframework.util.StringUtils; - -/** Canonical Entity-owned actor identity and the provenance disposition that gates its use. */ -public record ActorIdentity( - UUID characterUuid, - UUID accountUuid, - UUID tenantUuid, - UUID playableStateNamespaceId, - PlayableStateScope playableStateScope, - ActorIdentityStatus status, - String quarantineReason) { - - private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final String UUID_PATTERN = - "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; - - public ActorIdentity { - requireNonNil(characterUuid, "characterUuid"); - requireNonNilWhenPresent(accountUuid, "accountUuid"); - requireNonNilWhenPresent(tenantUuid, "tenantUuid"); - requireNonNilWhenPresent(playableStateNamespaceId, "playableStateNamespaceId"); - Objects.requireNonNull(status, "status"); - if (playableStateScope != null) { - requireScope(playableStateScope); - } - if (status == ActorIdentityStatus.OWNER_RESOLVED) { - requireNonNil(accountUuid, "accountUuid"); - requireNonNil(tenantUuid, "tenantUuid"); - requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); - requireScope(playableStateScope); - if (StringUtils.hasText(quarantineReason)) { - throw new IllegalArgumentException( - "owner-resolved identity cannot have a quarantine reason"); - } - } else if (!StringUtils.hasText(quarantineReason)) { - throw new IllegalArgumentException("quarantined identity requires a reason"); - } - } - - public static UUID parseRequiredUuid(String value, String fieldName) { - if (!StringUtils.hasText(value) || !value.matches(UUID_PATTERN)) { - throw new IllegalArgumentException(fieldName + " must be a canonical UUID"); - } - UUID parsed = UUID.fromString(value); - requireNonNil(parsed, fieldName); - return parsed; - } - - private static void requireNonNil(UUID value, String fieldName) { - if (value == null || NIL_UUID.equals(value)) { - throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); - } - } - - private static void requireNonNilWhenPresent(UUID value, String fieldName) { - if (value != null && NIL_UUID.equals(value)) { - throw new IllegalArgumentException(fieldName + " must not be the nil UUID"); - } - } - - public static PlayableStateScope requireScope(PlayableStateScope scope) { - if (scope == null - || (scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - && scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) { - throw new IllegalArgumentException("playableStateScope must be owner-resolved"); - } - return scope; - } -} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java deleted file mode 100644 index 67bcce21ee..0000000000 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java +++ /dev/null @@ -1,6 +0,0 @@ -package net.firedevops.firemud.entitymanagement.entity; - -public enum ActorIdentityStatus { - OWNER_RESOLVED, - QUARANTINED -} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java index 9056764770..935b98a45c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java @@ -11,7 +11,6 @@ @EqualsAndHashCode(onlyExplicitlyIncluded = true) public class Character { @EqualsAndHashCode.Include private Long id; - private ActorIdentity actorIdentity; private Long tenantId; private Long accountId; private String playableStateKey; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java index 4187236beb..80f448eb72 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java @@ -14,7 +14,6 @@ public interface CharacterMapper { @Mapping(target = "lastLoginAt", ignore = true) @Mapping(target = "playableStateKey", ignore = true) @Mapping(target = "bodyLayoutKey", constant = "DEFAULT") - @Mapping(target = "actorIdentity", ignore = true) @Mapping(target = "version", ignore = true) Character toEntity(CharacterDto dto); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java index c319b84651..bc84020bf9 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java @@ -2,7 +2,6 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; import static net.firedevops.firemud.entitymanagement.jooq.Tables.ACTOR_ACTIVE_CONDITIONS; -import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; @@ -11,7 +10,6 @@ import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; import org.jooq.DSLContext; import org.jooq.Record; -import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -34,7 +32,6 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) - .and(ownerResolvedActorExists()) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -62,7 +59,6 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) - .and(ownerResolvedActorExists()) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) @@ -71,7 +67,6 @@ public List findActiveForCharacter( } public ActorActiveCondition save(ActorActiveCondition entity) { - requireOwnerResolvedActor(entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_ACTIVE_CONDITIONS) @@ -92,30 +87,18 @@ public ActorActiveCondition save(ActorActiveCondition entity) { entity.setId(id); return entity; } - int updatedRows = - dsl.update(ACTOR_ACTIVE_CONDITIONS) - .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) - .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) - .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.VERSION, entity.getVersion() + 1) - .where( - ACTOR_ACTIVE_CONDITIONS - .ID - .eq(entity.getId()) - .and(ACTOR_ACTIVE_CONDITIONS.TENANT_ID.eq(entity.getTenantId())) - .and( - ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(entity.getPlayableStateKey())) - .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(entity.getCharacterId())) - .and(ownerResolvedActorExists())) - .execute(); - if (updatedRows != 1) { - throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - } + dsl.update(ACTOR_ACTIVE_CONDITIONS) + .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) + .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) + .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) + .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) + .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) + .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) + .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) + .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + .set(ACTOR_ACTIVE_CONDITIONS.VERSION, entity.getVersion() + 1) + .where(ACTOR_ACTIVE_CONDITIONS.ID.eq(entity.getId())) + .execute(); entity.setVersion(entity.getVersion() + 1); return entity; } @@ -126,37 +109,10 @@ public int deleteExpired(Instant now) { ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT .isNotNull() - .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now))) - .and(ownerResolvedActorExists())) + .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now)))) .execute(); } - private org.jooq.Condition ownerResolvedActorExists() { - return DSL.exists( - dsl.selectOne() - .from(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID) - .and(CHARACTERS.TENANT_ID.eq(ACTOR_ACTIVE_CONDITIONS.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); - } - - private void requireOwnerResolvedActor(Long tenantId, Long characterId) { - long ownerResolvedCount = - dsl.fetchCount( - CHARACTERS, - CHARACTERS - .ID - .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); - if (ownerResolvedCount != 1) { - throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - } - } - private ActorActiveCondition toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java deleted file mode 100644 index 83de1b6c5c..0000000000 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java +++ /dev/null @@ -1,105 +0,0 @@ -package net.firedevops.firemud.entitymanagement.repository; - -import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.springframework.stereotype.Repository; - -/** - * Exact, uncached canonical actor lookup. It intentionally has no write or resolution operation. - */ -@Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") -public class ActorIdentityRepository { - private final DSLContext dsl; - - public ActorIdentityRepository(DSLContext dsl) { - this.dsl = dsl; - } - - public List findOwnerResolvedRoster( - String tenantUuid, - String accountUuid, - String playableStateNamespaceId, - PlayableStateScope playableStateScope) { - UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); - UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); - UUID namespace = - ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); - PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); - return dsl.select( - CHARACTERS.CHARACTER_UUID, - CHARACTERS.ACCOUNT_UUID, - CHARACTERS.TENANT_UUID, - CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, - CHARACTERS.PLAYABLE_STATE_SCOPE, - CHARACTERS.ACTOR_IDENTITY_STATUS, - CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) - .from(CHARACTERS) - .where( - CHARACTERS - .ACTOR_IDENTITY_STATUS - .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) - .and(CHARACTERS.TENANT_UUID.eq(tenant)) - .and(CHARACTERS.ACCOUNT_UUID.eq(account)) - .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) - .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name()))) - .orderBy(CHARACTERS.CHARACTER_UUID.asc()) - .fetch(this::toIdentity); - } - - public Optional findOwnerResolvedActor( - String tenantUuid, - String accountUuid, - String playableStateNamespaceId, - PlayableStateScope playableStateScope, - String characterUuid) { - UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); - UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); - UUID namespace = - ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); - PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); - UUID requestedCharacter = ActorIdentity.parseRequiredUuid(characterUuid, "characterUuid"); - return Optional.ofNullable( - dsl.select( - CHARACTERS.CHARACTER_UUID, - CHARACTERS.ACCOUNT_UUID, - CHARACTERS.TENANT_UUID, - CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, - CHARACTERS.PLAYABLE_STATE_SCOPE, - CHARACTERS.ACTOR_IDENTITY_STATUS, - CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) - .from(CHARACTERS) - .where( - CHARACTERS - .ACTOR_IDENTITY_STATUS - .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) - .and(CHARACTERS.TENANT_UUID.eq(tenant)) - .and(CHARACTERS.ACCOUNT_UUID.eq(account)) - .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) - .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name())) - .and(CHARACTERS.CHARACTER_UUID.eq(requestedCharacter))) - .fetchOne(this::toIdentity)); - } - - private ActorIdentity toIdentity(Record record) { - return new ActorIdentity( - record.get(CHARACTERS.CHARACTER_UUID), - record.get(CHARACTERS.ACCOUNT_UUID), - record.get(CHARACTERS.TENANT_UUID), - record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), - PlayableStateScope.valueOf(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), - ActorIdentityStatus.valueOf(record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), - record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON)); - } -} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 7cf103b979..478bd81341 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java @@ -2,14 +2,12 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; import static net.firedevops.firemud.entitymanagement.jooq.Tables.ACTOR_RESOURCE_STATES; -import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; import org.jooq.DSLContext; import org.jooq.Record; -import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -31,14 +29,12 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO .TENANT_ID .eq(tenantId) .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId)) - .and(ownerResolvedActorExists())) + .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } public ActorResourceState save(ActorResourceState entity) { - requireOwnerResolvedActor(entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_RESOURCE_STATES) @@ -58,57 +54,20 @@ public ActorResourceState save(ActorResourceState entity) { entity.setId(id); return entity; } - int updatedRows = - dsl.update(ACTOR_RESOURCE_STATES) - .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) - .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) - .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) - .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) - .set(ACTOR_RESOURCE_STATES.VERSION, entity.getVersion() + 1) - .where( - ACTOR_RESOURCE_STATES - .ID - .eq(entity.getId()) - .and(ACTOR_RESOURCE_STATES.TENANT_ID.eq(entity.getTenantId())) - .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(entity.getPlayableStateKey())) - .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(entity.getCharacterId())) - .and(ownerResolvedActorExists())) - .execute(); - if (updatedRows != 1) { - throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - } + dsl.update(ACTOR_RESOURCE_STATES) + .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) + .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) + .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) + .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) + .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) + .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + .set(ACTOR_RESOURCE_STATES.VERSION, entity.getVersion() + 1) + .where(ACTOR_RESOURCE_STATES.ID.eq(entity.getId())) + .execute(); entity.setVersion(entity.getVersion() + 1); return entity; } - private void requireOwnerResolvedActor(Long tenantId, Long characterId) { - long ownerResolvedCount = - dsl.fetchCount( - CHARACTERS, - CHARACTERS - .ID - .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); - if (ownerResolvedCount != 1) { - throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - } - } - - private org.jooq.Condition ownerResolvedActorExists() { - return DSL.exists( - dsl.selectOne() - .from(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(ACTOR_RESOURCE_STATES.CHARACTER_ID) - .and(CHARACTERS.TENANT_ID.eq(ACTOR_RESOURCE_STATES.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); - } - private ActorResourceState toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java index c8caf02fd4..acfd6bd865 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java @@ -35,8 +35,7 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + .and(CHARACTERS.TENANT_ID.eq(tenantId)))); var content = dsl.select( CHARACTER_EQUIPMENT.CHARACTER_ID, @@ -69,8 +68,7 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .and(CHARACTERS.TENANT_ID.eq(tenantId))) .orderBy(CHARACTER_EQUIPMENT.SLOT.asc()) .limit( JooqEntityManagementRepositorySupport.limitOrDefault(pageable, Integer.MAX_VALUE)) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java index ef9c9da515..a206dbbc9a 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java @@ -1,17 +1,14 @@ package net.firedevops.firemud.entitymanagement.repository; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; -import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTER_FRIEND; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; import org.jooq.DSLContext; import org.jooq.Record; -import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @@ -28,11 +25,10 @@ public CharacterFriendRepository(DSLContext dsl) { } public Page findByIdCharacterId(Long characterId, Pageable pageable) { - var condition = CHARACTER_FRIEND.CHARACTER_ID.eq(characterId).and(ownerResolvedPair()); - long total = dsl.fetchCount(CHARACTER_FRIEND, condition); + long total = dsl.fetchCount(CHARACTER_FRIEND, CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)); var content = dsl.selectFrom(CHARACTER_FRIEND) - .where(condition) + .where(CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)) .orderBy(CHARACTER_FRIEND.FRIEND_ID.asc()) .limit(limitOrDefault(pageable, Integer.MAX_VALUE)) .offset(offsetOrZero(pageable)) @@ -51,26 +47,11 @@ public Optional findById(CharacterFriendKey key) { CHARACTER_FRIEND .CHARACTER_ID .eq(key.getCharacterId()) - .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId())) - .and(ownerResolvedPair())) + .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId()))) .fetchOne(this::toEntity)); } public CharacterFriend save(CharacterFriend entity) { - if (Objects.equals(entity.getId().getCharacterId(), entity.getId().getFriendId())) { - throw new IllegalStateException("FRIEND_SELF_RELATIONSHIP_NOT_ALLOWED"); - } - long ownerResolvedCount = - dsl.fetchCount( - CHARACTERS, - CHARACTERS - .ID - .in(entity.getId().getCharacterId(), entity.getId().getFriendId()) - .and(CHARACTERS.TENANT_ID.eq(entity.getTenantId())) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); - if (ownerResolvedCount != 2) { - throw new IllegalStateException("FRIEND_ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - } if (findById(entity.getId()).isEmpty()) { dsl.insertInto(CHARACTER_FRIEND) .set(CHARACTER_FRIEND.CHARACTER_ID, entity.getId().getCharacterId()) @@ -88,35 +69,10 @@ public void deleteById(CharacterFriendKey key) { CHARACTER_FRIEND .CHARACTER_ID .eq(key.getCharacterId()) - .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId())) - .and(ownerResolvedPair())) + .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId()))) .execute(); } - private org.jooq.Condition ownerResolvedPair() { - var ownerResolvedCharacter = - DSL.exists( - dsl.selectOne() - .from(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(CHARACTER_FRIEND.CHARACTER_ID) - .and(CHARACTERS.TENANT_ID.eq(CHARACTER_FRIEND.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); - var ownerResolvedFriend = - DSL.exists( - dsl.selectOne() - .from(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(CHARACTER_FRIEND.FRIEND_ID) - .and(CHARACTERS.TENANT_ID.eq(CHARACTER_FRIEND.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); - return ownerResolvedCharacter.and(ownerResolvedFriend); - } - private CharacterFriend toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 8a219fcebf..9e2d219ee4 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -8,7 +8,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.LinkedHashSet; import java.util.Optional; -import java.util.UUID; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.InventoryEntry; import net.firedevops.firemud.entitymanagement.entity.InventoryKey; @@ -33,9 +32,7 @@ public CharacterRepository(DSLContext dsl) { public Optional findWithInventoryById(Long id) { Character character = - dsl.selectFrom(CHARACTERS) - .where(CHARACTERS.ID.eq(id).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) - .fetchOne(this::toEntity); + dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity); if (character == null) { return Optional.empty(); } @@ -68,20 +65,13 @@ public Optional findWithInventoryById(Long id) { public Optional findById(Long id) { return Optional.ofNullable( - dsl.selectFrom(CHARACTERS) - .where(CHARACTERS.ID.eq(id).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) - .fetchOne(this::toEntity)); + dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity)); } public Optional findByIdAndTenantId(Long id, Long tenantId) { return Optional.ofNullable( dsl.selectFrom(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(id) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .where(CHARACTERS.ID.eq(id).and(CHARACTERS.TENANT_ID.eq(tenantId))) .fetchOne(this::toEntity)); } @@ -94,8 +84,7 @@ public Optional findByIdAndTenantIdAndPlayableStateKey( .ID .eq(id) .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey))) .fetchOne(this::toEntity)); } @@ -106,8 +95,7 @@ public Page findByTenantIdAndAccountIdAndPlayableStateKey( .TENANT_ID .eq(tenantId) .and(CHARACTERS.ACCOUNT_ID.eq(accountId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")); + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)); long total = dsl.fetchCount(CHARACTERS, condition); var content = dsl.selectFrom(CHARACTERS) @@ -130,8 +118,7 @@ public Optional findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( .TENANT_ID .eq(tenantId) .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase())) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase()))) .limit(1) .fetchOne(this::toEntity)); } @@ -140,20 +127,10 @@ public long countByTenantId(Long tenantId) { return dsl.fetchCount(CHARACTERS, CHARACTERS.TENANT_ID.eq(tenantId)); } - public long countQuarantinedByTenantId(Long tenantId) { - return dsl.fetchCount( - CHARACTERS, - CHARACTERS.TENANT_ID.eq(tenantId).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("QUARANTINED"))); - } - public Character save(Character entity) { if (entity.getId() == null) { - UUID characterUuid = UUID.randomUUID(); Long id = dsl.insertInto(CHARACTERS) - .set(CHARACTERS.CHARACTER_UUID, characterUuid) - .set(CHARACTERS.ACTOR_IDENTITY_STATUS, "QUARANTINED") - .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, "OWNER_PROVENANCE_MISSING") .set(CHARACTERS.TENANT_ID, entity.getTenantId()) .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) @@ -171,35 +148,27 @@ public Character save(Character entity) { .set(CHARACTERS.VERSION, entity.getVersion()) .returningResult(CHARACTERS.ID) .fetchOne(CHARACTERS.ID); - return findStoredById(id).orElseThrow(); - } - int updatedRows = - dsl.update(CHARACTERS) - .set(CHARACTERS.TENANT_ID, entity.getTenantId()) - .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) - .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) - .set(CHARACTERS.NAME, entity.getName()) - .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) - .set(CHARACTERS.LEVEL, entity.getLevel()) - .set(CHARACTERS.EXPERIENCE, entity.getExperience()) - .set(CHARACTERS.STRENGTH, entity.getStrength()) - .set(CHARACTERS.AGILITY, entity.getAgility()) - .set(CHARACTERS.INTELLIGENCE, entity.getIntelligence()) - .set(CHARACTERS.STAMINA, entity.getStamina()) - .set(CHARACTERS.HEALTH, entity.getHealth()) - .set(CHARACTERS.MANA, entity.getMana()) - .set(CHARACTERS.LAST_LOGIN_AT, toLocalDateTime(entity.getLastLoginAt())) - .set(CHARACTERS.VERSION, entity.getVersion() + 1) - .where( - CHARACTERS - .ID - .eq(entity.getId()) - .and(CHARACTERS.TENANT_ID.eq(entity.getTenantId())) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) - .execute(); - if (updatedRows != 1) { - throw new IllegalStateException("CHARACTER_IDENTITY_NOT_OWNER_RESOLVED"); + return findById(id).orElseThrow(); } + dsl.update(CHARACTERS) + .set(CHARACTERS.TENANT_ID, entity.getTenantId()) + .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) + .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) + .set(CHARACTERS.NAME, entity.getName()) + .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) + .set(CHARACTERS.LEVEL, entity.getLevel()) + .set(CHARACTERS.EXPERIENCE, entity.getExperience()) + .set(CHARACTERS.STRENGTH, entity.getStrength()) + .set(CHARACTERS.AGILITY, entity.getAgility()) + .set(CHARACTERS.INTELLIGENCE, entity.getIntelligence()) + .set(CHARACTERS.STAMINA, entity.getStamina()) + .set(CHARACTERS.HEALTH, entity.getHealth()) + .set(CHARACTERS.MANA, entity.getMana()) + .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) + .set(CHARACTERS.LAST_LOGIN_AT, toLocalDateTime(entity.getLastLoginAt())) + .set(CHARACTERS.VERSION, entity.getVersion() + 1) + .where(CHARACTERS.ID.eq(entity.getId())) + .execute(); return findById(entity.getId()).orElseThrow(); } @@ -209,16 +178,6 @@ private Character toEntity(Record record) { } Character character = new Character(); character.setId(record.get(CHARACTERS.ID)); - character.setActorIdentity( - new net.firedevops.firemud.entitymanagement.entity.ActorIdentity( - record.get(CHARACTERS.CHARACTER_UUID), - record.get(CHARACTERS.ACCOUNT_UUID), - record.get(CHARACTERS.TENANT_UUID), - record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), - scopeFrom(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), - net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus.valueOf( - record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), - record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON))); character.setTenantId(record.get(CHARACTERS.TENANT_ID)); character.setAccountId(record.get(CHARACTERS.ACCOUNT_ID)); character.setPlayableStateKey(record.get(CHARACTERS.PLAYABLE_STATE_KEY)); @@ -237,17 +196,6 @@ private Character toEntity(Record record) { return character; } - private Optional findStoredById(Long id) { - return Optional.ofNullable( - dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity)); - } - - private net.firedevops.firemud.entitymanagement.v1.PlayableStateScope scopeFrom(String value) { - return value == null - ? null - : net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf(value); - } - private InventoryEntry toInventoryEntry(Record record, Character character) { InventoryEntry entry = new InventoryEntry(); InventoryKey key = new InventoryKey(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java deleted file mode 100644 index eea689b28b..0000000000 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.firedevops.firemud.entitymanagement.repository; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.jooq.impl.DSL; -import org.springframework.stereotype.Repository; - -/** Detects unclassified runtime rows and quarantined-actor audit evidence before cleanup. */ -@Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") -public class QuarantinedActorRetentionRepository { - private static final String HAS_UNCLASSIFIED_OR_QUARANTINED_RUNTIME_EVIDENCE_SQL = - """ - WITH target AS ( - SELECT CAST(? AS BIGINT) AS tenant_id, - CAST(? AS TEXT) AS game_instance_id - ) - SELECT - CAST((EXISTS ( - SELECT 1 - FROM item_instances item_instance - CROSS JOIN target - WHERE item_instance.tenant_id = target.tenant_id - AND item_instance.game_instance_id = target.game_instance_id - ) - OR EXISTS ( - SELECT 1 - FROM container_instances container - CROSS JOIN target - WHERE container.tenant_id = target.tenant_id - AND container.game_instance_id = target.game_instance_id - ) - OR EXISTS ( - SELECT 1 - FROM item_stacks stack - CROSS JOIN target - WHERE stack.tenant_id = target.tenant_id - AND stack.game_instance_id = target.game_instance_id - ) - OR EXISTS ( - SELECT 1 - FROM room_ground_inventory ground - CROSS JOIN target - WHERE ground.tenant_id = target.tenant_id - AND ground.game_instance_id = target.game_instance_id - ) - OR EXISTS ( - SELECT 1 - FROM item_transfer_audits audit - JOIN characters actor - ON actor.tenant_id = audit.tenant_id - AND actor.actor_identity_status = 'QUARANTINED' - AND ( - actor.id = audit.actor_character_id - OR actor.id = audit.source_character_id - OR actor.id = audit.destination_character_id - ) - CROSS JOIN target - WHERE audit.tenant_id = target.tenant_id - AND ( - audit.source_game_instance_id = target.game_instance_id - OR audit.destination_game_instance_id = target.game_instance_id - ) - )) AS BOOLEAN) - """; - - private final DSLContext dsl; - - public QuarantinedActorRetentionRepository(DSLContext dsl) { - this.dsl = dsl; - } - - public boolean hasUnclassifiedOrQuarantinedRuntimeEvidence(Long tenantId, String gameInstanceId) { - Record result = - dsl.fetchOne( - DSL.sql( - HAS_UNCLASSIFIED_OR_QUARANTINED_RUNTIME_EVIDENCE_SQL, tenantId, gameInstanceId)); - if (result == null) { - throw new IllegalStateException("RUNTIME_EVIDENCE_READBACK_UNAVAILABLE"); - } - Boolean retained = result.get(0, Boolean.class); - if (retained == null) { - throw new IllegalStateException("RUNTIME_EVIDENCE_READBACK_UNAVAILABLE"); - } - return retained; - } -} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java index 8bcd28175a..26283287d5 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java @@ -1,25 +1,31 @@ package net.firedevops.firemud.entitymanagement.service; -import java.util.Objects; +import lombok.RequiredArgsConstructor; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.springframework.stereotype.Service; @Service -public final class ScopedCharacterResolver { - public ScopedCharacterResolver( - CharacterRepository characterRepository, PlayableStateKeyResolver playableStateKeyResolver) { - Objects.requireNonNull(characterRepository); - Objects.requireNonNull(playableStateKeyResolver); - } +@RequiredArgsConstructor +public class ScopedCharacterResolver { + private final CharacterRepository characterRepository; + private final PlayableStateKeyResolver playableStateKeyResolver; public Character requireScopedCharacter( Long tenantId, Long characterId, String gameInstanceId, PlayableStateScope playableStateScope) { - throw new IllegalArgumentException( - "OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED: legacy playableStateKey and runtime scope do not prove actor ownership"); + String playableStateKey = playableStateKeyResolver.resolve(gameInstanceId, playableStateScope); + return characterRepository + .findByIdAndTenantIdAndPlayableStateKey(characterId, tenantId, playableStateKey) + .or( + () -> + characterRepository + .findByIdAndTenantId(characterId, tenantId) + .filter(character -> playableStateKey.equals(character.getPlayableStateKey()))) + .orElseThrow( + () -> new IllegalArgumentException("Character does not belong to gameplay scope")); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java index c3f2886084..a6ec5bb285 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java @@ -1,6 +1,10 @@ package net.firedevops.firemud.entitymanagement.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.entitymanagement.dto.CharacterDto; import net.firedevops.firemud.entitymanagement.entity.Character; @@ -10,6 +14,8 @@ import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -17,15 +23,29 @@ @Service @RequiredArgsConstructor +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected dependencies are not exposed") public class CharacterServiceImpl implements CharacterService { private final CharacterRepository characterRepository; private final CharacterMapper characterMapper; + private final CacheManager cacheManager; + private final MeterRegistry meterRegistry; private final PlayableStateKeyResolver playableStateKeyResolver; private final ScopedCharacterResolver scopedCharacterResolver; + private Counter cacheHitCounter; + private Counter cacheMissCounter; + private static final int EXP_PER_LEVEL = 1000; + @PostConstruct + void initMetrics() { + cacheHitCounter = meterRegistry.counter("character_cache_hits_total"); + cacheMissCounter = meterRegistry.counter("character_cache_misses_total"); + } + @Override @Transactional @Timed(value = "character.create") @@ -57,9 +77,21 @@ public CharacterDto create( @Transactional(readOnly = true) @Timed(value = "character.get") public CharacterDto getWithInventory(Long characterId) { - // Rely exclusively on the repository's fresh persisted OWNER_RESOLVED predicate. + Cache cache = cacheManager.getCache("characterGraph"); + if (cache != null) { + CharacterDto cached = cache.get(characterId, CharacterDto.class); + if (cached != null) { + cacheHitCounter.increment(); + return cached; + } + } + cacheMissCounter.increment(); Character character = characterRepository.findWithInventoryById(characterId).orElseThrow(); - return toDto(character); + CharacterDto dto = toDto(character); + if (cache != null) { + cache.put(characterId, dto); + } + return dto; } @Override @@ -108,7 +140,13 @@ public Page listForGameplayScope( String gameInstanceId, PlayableStateScope playableStateScope, Pageable pageable) { - return Page.empty(pageable == null ? Pageable.unpaged() : pageable); + return characterRepository + .findByTenantIdAndAccountIdAndPlayableStateKey( + tenantId, + accountId, + playableStateKeyResolver.resolve(gameInstanceId, playableStateScope), + pageable) + .map(this::toDto); } @Override @@ -119,7 +157,12 @@ public java.util.Optional findByGameplayScopeAndName( if (name == null || name.isBlank()) { return java.util.Optional.empty(); } - return java.util.Optional.empty(); + return characterRepository + .findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( + tenantId, + playableStateKeyResolver.resolve(gameInstanceId, playableStateScope), + name.trim()) + .map(this::toDto); } private CharacterDto toDto(Character character) { @@ -129,12 +172,7 @@ private CharacterDto toDto(Character character) { dto.tenantId(), dto.accountId(), dto.name(), - character.getActorIdentity() == null - || character.getActorIdentity().status() - != net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus - .OWNER_RESOLVED - ? PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED - : character.getActorIdentity().playableStateScope(), + playableStateKeyResolver.resolveScope(character.getPlayableStateKey()), dto.level(), dto.experience(), dto.strength(), diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java index 7f1e246fe5..eb907e418d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java @@ -65,7 +65,7 @@ public EntityUpgradeValidationServiceImpl( public EntityUpgradeValidationResultDto validateEntityUpgradeMappings( long tenantId, long sourceGameInstanceId, long targetVersionId, String remapSetId) { String gameInstanceId = Long.toString(sourceGameInstanceId); - long quarantinedActors = characterRepository.countQuarantinedByTenantId(tenantId); + characterRepository.countByTenantId(tenantId); long inventoryRows = inventoryEntryRepository.countByCharacterTenantId(tenantId); long equipmentRows = characterEquipmentRepository.countByCharacterTenantId(tenantId); characterFriendRepository.countByTenantId(tenantId); @@ -75,17 +75,6 @@ public EntityUpgradeValidationResultDto validateEntityUpgradeMappings( roomGroundInventoryRepository.countByIdTenantIdAndIdGameInstanceId(tenantId, gameInstanceId); String normalizedRemapSetId = normalizeBlank(remapSetId); boolean hasTemplateBoundRows = inventoryRows > 0 || equipmentRows > 0; - if (quarantinedActors > 0) { - return new EntityUpgradeValidationResultDto( - STATE_CLASSES, - CHECKED_FAMILIES, - hasTemplateBoundRows, - "INCOMPATIBLE", - false, - List.of( - "ENTITY_ACTOR_IDENTITY_QUARANTINED: legacy actor identity lacks exact Account UUID and owner-resolved namespace/scope provenance"), - null); - } if (hasTemplateBoundRows && normalizedRemapSetId == null) { return new EntityUpgradeValidationResultDto( STATE_CLASSES, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java index 41f3ceea4b..35532752c1 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java @@ -1,18 +1,34 @@ package net.firedevops.firemud.entitymanagement.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import net.firedevops.firemud.entitymanagement.dto.RuntimeInstanceCleanupResultDto; -import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; +import net.firedevops.firemud.entitymanagement.repository.ContainerInstanceRepository; +import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; +import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; +import net.firedevops.firemud.entitymanagement.repository.RoomGroundInventoryRepository; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories are managed dependencies kept internal.") public class RuntimeInstanceCleanupServiceImpl implements RuntimeInstanceCleanupService { - private final QuarantinedActorRetentionRepository quarantinedActorRetentionRepository; + private final RoomGroundInventoryRepository roomGroundInventoryRepository; + private final ItemStackRepository itemStackRepository; + private final ItemInstanceRepository itemInstanceRepository; + private final ContainerInstanceRepository containerInstanceRepository; public RuntimeInstanceCleanupServiceImpl( - QuarantinedActorRetentionRepository quarantinedActorRetentionRepository) { - this.quarantinedActorRetentionRepository = quarantinedActorRetentionRepository; + RoomGroundInventoryRepository roomGroundInventoryRepository, + ItemStackRepository itemStackRepository, + ItemInstanceRepository itemInstanceRepository, + ContainerInstanceRepository containerInstanceRepository) { + this.roomGroundInventoryRepository = roomGroundInventoryRepository; + this.itemStackRepository = itemStackRepository; + this.itemInstanceRepository = itemInstanceRepository; + this.containerInstanceRepository = containerInstanceRepository; } @Override @@ -28,11 +44,19 @@ public RuntimeInstanceCleanupResultDto cleanupRuntimeInstance( if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } - if (quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - tenantId, gameInstanceId)) { - throw new IllegalStateException( - "ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP: runtime rows lack owner classification or quarantined actor audit evidence is present"); - } - return new RuntimeInstanceCleanupResultDto(0, 0, 0, 0); + long deletedRoomGroundEntries = + roomGroundInventoryRepository.deleteByIdTenantIdAndIdGameInstanceId( + tenantId, gameInstanceId); + long deletedItemStacks = + itemStackRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); + long deletedItemInstances = + itemInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); + long deletedContainerInstances = + containerInstanceRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); + return new RuntimeInstanceCleanupResultDto( + deletedRoomGroundEntries, + deletedItemStacks, + deletedItemInstances, + deletedContainerInstances); } } diff --git a/services/entity-management-service/src/main/resources/application-prod.yml b/services/entity-management-service/src/main/resources/application-prod.yml index 5bd8518afb..fd6533c6f2 100644 --- a/services/entity-management-service/src/main/resources/application-prod.yml +++ b/services/entity-management-service/src/main/resources/application-prod.yml @@ -4,8 +4,6 @@ spring: name: entity-management-service flyway: enabled: true - postgresql: - transactional-lock: false schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index 54a96253b4..d3b5e99641 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -3,8 +3,6 @@ spring: name: entity-management-service flyway: enabled: true - postgresql: - transactional-lock: false schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} diff --git a/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql b/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql deleted file mode 100644 index 2022ded057..0000000000 --- a/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql +++ /dev/null @@ -1,172 +0,0 @@ -CREATE TABLE entity_playable_state_namespace_scopes ( - tenant_uuid UUID NOT NULL, - playable_state_namespace_id UUID NOT NULL, - playable_state_scope VARCHAR(40) NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT pk_entity_playable_state_namespace_scopes - PRIMARY KEY (tenant_uuid, playable_state_namespace_id), - CONSTRAINT ck_entity_playable_state_namespace_scope - CHECK (playable_state_scope IN ( - 'PLAYABLE_STATE_SCOPE_SHARED', - 'PLAYABLE_STATE_SCOPE_ISOLATED' - )), - CONSTRAINT ck_entity_playable_state_namespace_tenant_non_nil - CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), - CONSTRAINT ck_entity_playable_state_namespace_id_non_nil - CHECK (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID), - CONSTRAINT ux_entity_playable_state_namespace_scope - UNIQUE (tenant_uuid, playable_state_namespace_id, playable_state_scope) -); - -/* [jooq ignore start] */ -CREATE FUNCTION reject_entity_playable_state_namespace_scope_change() -RETURNS TRIGGER -LANGUAGE plpgsql -AS $$ -BEGIN - IF (NEW.tenant_uuid, NEW.playable_state_namespace_id, NEW.playable_state_scope) - IS DISTINCT FROM - (OLD.tenant_uuid, OLD.playable_state_namespace_id, OLD.playable_state_scope) THEN - RAISE EXCEPTION 'entity playable-state namespace identity is immutable' - USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; - -CREATE TRIGGER trg_entity_playable_state_namespace_scopes_immutable - BEFORE UPDATE OF tenant_uuid, playable_state_namespace_id, playable_state_scope - ON entity_playable_state_namespace_scopes - FOR EACH ROW - EXECUTE FUNCTION reject_entity_playable_state_namespace_scope_change(); -/* [jooq ignore stop] */ - -ALTER TABLE characters - ADD COLUMN character_uuid UUID, - ADD COLUMN account_uuid UUID, - ADD COLUMN tenant_uuid UUID, - ADD COLUMN playable_state_namespace_id UUID, - ADD COLUMN playable_state_scope VARCHAR(40), - ADD COLUMN actor_identity_status VARCHAR(24) NOT NULL DEFAULT 'QUARANTINED', - ADD COLUMN actor_identity_quarantine_reason VARCHAR(80) - DEFAULT 'OWNER_PROVENANCE_MISSING'; - -UPDATE characters -SET character_uuid = gen_random_uuid(), - actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING'; - --- This retained-row backfill updates every existing character in one migration transaction. --- Quiesce Entity character writes for this migration; it is not an online activation procedure. -ALTER TABLE characters - ALTER COLUMN character_uuid SET DEFAULT gen_random_uuid(); - -/* [jooq ignore start] */ -ALTER TABLE characters - ADD CONSTRAINT ck_characters_character_uuid_nonnull - CHECK (character_uuid IS NOT NULL) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT ck_characters_character_uuid_non_nil - CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT ck_characters_actor_identity_status - CHECK (actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED')) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT ck_characters_actor_identity_quarantine_reason - CHECK ( - (actor_identity_status = 'QUARANTINED' - AND actor_identity_quarantine_reason IS NOT NULL - AND length(trim(actor_identity_quarantine_reason)) > 0) - OR (actor_identity_status = 'OWNER_RESOLVED' - AND actor_identity_quarantine_reason IS NULL) - ) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT ck_characters_actor_identity_uuid_non_nil - CHECK ( - (account_uuid IS NULL OR account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) - AND (tenant_uuid IS NULL OR tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) - AND (playable_state_namespace_id IS NULL OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID) - ) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT ck_characters_actor_identity_scope - CHECK ( - playable_state_scope IS NULL - OR playable_state_scope IN ( - 'PLAYABLE_STATE_SCOPE_SHARED', - 'PLAYABLE_STATE_SCOPE_ISOLATED' - ) - ) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT ck_characters_owner_resolved_provenance - CHECK ( - actor_identity_status <> 'OWNER_RESOLVED' - OR ( - account_uuid IS NOT NULL - AND tenant_uuid IS NOT NULL - AND playable_state_namespace_id IS NOT NULL - AND playable_state_scope IS NOT NULL - ) - ) NOT VALID; - -ALTER TABLE characters - ADD CONSTRAINT fk_characters_owner_resolved_namespace_scope - FOREIGN KEY (tenant_uuid, playable_state_namespace_id, playable_state_scope) - REFERENCES entity_playable_state_namespace_scopes ( - tenant_uuid, - playable_state_namespace_id, - playable_state_scope - ) NOT VALID; -/* [jooq ignore stop] */ - -/* [jooq ignore start] */ -CREATE VIEW entity_quarantined_actor_item_instances AS -WITH RECURSIVE retained_item_instances(tenant_id, item_instance_id) AS ( - SELECT item_instance.tenant_id, item_instance.id - FROM item_instances item_instance - JOIN characters actor - ON actor.id = item_instance.character_id - AND actor.actor_identity_status = 'QUARANTINED' - - UNION - - SELECT container.tenant_id, container.item_instance_id - FROM container_instances container - JOIN characters actor - ON actor.id = container.character_id - AND actor.actor_identity_status = 'QUARANTINED' - WHERE container.item_instance_id IS NOT NULL - - UNION - - SELECT child_item.tenant_id, child_item.id - FROM retained_item_instances retained_parent - JOIN container_instances parent_container - ON parent_container.tenant_id = retained_parent.tenant_id - AND parent_container.item_instance_id = retained_parent.item_instance_id - JOIN item_instances child_item - ON child_item.tenant_id = parent_container.tenant_id - AND child_item.container_instance_id = parent_container.id -) -SELECT DISTINCT tenant_id, item_instance_id -FROM retained_item_instances; - -CREATE VIEW entity_quarantined_actor_container_instances AS -SELECT DISTINCT container.tenant_id, container.id AS container_instance_id -FROM container_instances container -JOIN characters actor - ON actor.id = container.character_id - AND actor.actor_identity_status = 'QUARANTINED' - -UNION - -SELECT DISTINCT container.tenant_id, container.id AS container_instance_id -FROM container_instances container -JOIN entity_quarantined_actor_item_instances retained_item - ON retained_item.tenant_id = container.tenant_id - AND retained_item.item_instance_id = container.item_instance_id; -/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql b/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql deleted file mode 100644 index da86ec481a..0000000000 --- a/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql +++ /dev/null @@ -1,20 +0,0 @@ -/* [jooq ignore start] */ -CREATE UNIQUE INDEX CONCURRENTLY ux_characters_character_uuid_idx - ON characters (character_uuid); - -CREATE INDEX CONCURRENTLY idx_characters_owner_resolved_roster - ON characters ( - tenant_uuid, - account_uuid, - playable_state_namespace_id, - playable_state_scope, - character_uuid - ) - WHERE actor_identity_status = 'OWNER_RESOLVED'; -/* [jooq ignore stop] */ - -/* [jooq ignore start] */ -ALTER TABLE characters - ADD CONSTRAINT ux_characters_character_uuid - UNIQUE USING INDEX ux_characters_character_uuid_idx; -/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf b/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf deleted file mode 100644 index 73bd53a146..0000000000 --- a/services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf +++ /dev/null @@ -1 +0,0 @@ -executeInTransaction=false diff --git a/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql b/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql deleted file mode 100644 index 0a927a7853..0000000000 --- a/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql +++ /dev/null @@ -1,34 +0,0 @@ -/* [jooq ignore start] */ -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull; -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_character_uuid_non_nil; - -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_actor_identity_status; - -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_actor_identity_quarantine_reason; - -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_actor_identity_uuid_non_nil; - -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_actor_identity_scope; - -ALTER TABLE characters - VALIDATE CONSTRAINT ck_characters_owner_resolved_provenance; - -ALTER TABLE characters - VALIDATE CONSTRAINT fk_characters_owner_resolved_namespace_scope; -/* [jooq ignore stop] */ - --- Take the stronger lock only after all validation scans have completed. The validated --- non-null check remains present so PostgreSQL can avoid another full-table scan. -ALTER TABLE characters - ALTER COLUMN character_uuid SET NOT NULL; - -/* [jooq ignore start] */ -ALTER TABLE characters - DROP CONSTRAINT ck_characters_character_uuid_nonnull; -/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java index c4680f9717..c93c1e6813 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java @@ -2,9 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import java.util.HashMap; -import java.util.Map; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.Item; import net.firedevops.firemud.entitymanagement.entity.ItemStackCompatibilityMode; @@ -15,13 +12,11 @@ import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; import net.firedevops.firemud.entitymanagement.service.ContainerService; import net.firedevops.firemud.entitymanagement.service.InventoryService; -import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -36,12 +31,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** - * Conditional PostgreSQL proof for holder persistence after an assumed actor scope guard. The - * mocked resolver admits only explicitly registered saved-character fixtures with the exact test - * tenant, instance, and scope; those rows remain quarantined. This class proves nested holder and - * persistence behavior, not owner provenance, runtime admission, or PLAY activation. - */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @SpringBootTest( @@ -54,7 +43,6 @@ class ContainerInstanceLocationIntegrationTest { private static final String ROOM_INSTANCE_ID = "R-1"; private static final PlayableStateScope PLAYABLE_STATE_SCOPE = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - private final Map registeredCharacterFixtures = new HashMap<>(); @Container static PostgreSQLContainer postgres = @@ -81,34 +69,9 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private JdbcTemplate jdbcTemplate; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; - @MockitoBean private ScopedCharacterResolver scopedCharacterResolver; @BeforeEach void cleanDatabase() { - registeredCharacterFixtures.clear(); - Mockito.doAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long characterId = invocation.getArgument(1); - String gameInstanceId = invocation.getArgument(2); - PlayableStateScope playableStateScope = invocation.getArgument(3); - Character character = registeredCharacterFixtures.get(characterId); - if (!TENANT_ID.equals(tenantId) - || !GAME_INSTANCE_ID.equals(gameInstanceId) - || PLAYABLE_STATE_SCOPE != playableStateScope - || character == null - || !TENANT_ID.equals(character.getTenantId())) { - throw new IllegalArgumentException( - "Test scoped resolver fixture does not match requested tenant, character, instance, or scope"); - } - return character; - }) - .when(scopedCharacterResolver) - .requireScopedCharacter( - Mockito.nullable(Long.class), - Mockito.nullable(Long.class), - Mockito.nullable(String.class), - Mockito.nullable(PlayableStateScope.class)); jdbcTemplate.execute( "TRUNCATE TABLE item_stacks, item_instances, container_instances, items, characters RESTART IDENTITY CASCADE"); } @@ -117,8 +80,6 @@ void cleanDatabase() { void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { Character alice = characterRepository.save(character("Alice")); Character bob = characterRepository.save(character("Bob")); - registerCharacterFixture(alice); - registerCharacterFixture(bob); Item backpack = itemRepository.save(containerItem("Backpack")); Item torch = itemRepository.save(ordinaryItem("Torch")); @@ -225,7 +186,6 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { @Test void identicalContainersKeepDistinctContentsByContainerInstance() { Character alice = characterRepository.save(character("Alice")); - registerCharacterFixture(alice); Item backpack = itemRepository.save(containerItem("Backpack")); Item torch = itemRepository.save(ordinaryItem("Torch")); Item ration = itemRepository.save(ordinaryItem("Ration")); @@ -331,12 +291,6 @@ private Character character(String name) { return character; } - private void registerCharacterFixture(Character character) { - assertThat(character.getActorIdentity()).isNotNull(); - assertThat(character.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); - registeredCharacterFixtures.put(character.getId(), character); - } - private Item containerItem(String name) { Item item = ordinaryItem(name); item.setContainer(true); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java deleted file mode 100644 index b139d56f98..0000000000 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ /dev/null @@ -1,1152 +0,0 @@ -package net.firedevops.firemud.entitymanagement; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; -import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; -import net.firedevops.firemud.entitymanagement.entity.Character; -import net.firedevops.firemud.entitymanagement.repository.ActorActiveConditionRepository; -import net.firedevops.firemud.entitymanagement.repository.ActorIdentityRepository; -import net.firedevops.firemud.entitymanagement.repository.ActorResourceStateRepository; -import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; -import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; -import net.firedevops.firemud.entitymanagement.service.CharacterService; -import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; -import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; -import org.flywaydb.core.api.configuration.FluentConfiguration; -import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -@SpringBootTest( - webEnvironment = WebEnvironment.NONE, - classes = EntityManagementServiceApplication.class, - properties = "spring.grpc.server.port=0") -class RetainedActorIdentityIntegrationTest { - private static final long TENANT_ID = 72L; - private static final long ACCOUNT_ID = 88L; - private static final String INSTANCE_ID = "GI-RETAINED"; - private static final UUID TENANT_UUID = UUID.fromString("10000000-0000-4000-8000-000000000001"); - private static final UUID ACCOUNT_UUID = UUID.fromString("20000000-0000-4000-8000-000000000002"); - private static final UUID NAMESPACE_UUID = - UUID.fromString("30000000-0000-4000-8000-000000000003"); - private String migrationSchema; - - @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, "entity_management_service"); - PostgresBackedServiceTestSupport.registerRedisService(registry, redis); - } - - @Autowired private ActorIdentityRepository actorIdentityRepository; - @Autowired private CharacterRepository characterRepository; - @Autowired private ActorActiveConditionRepository actorActiveConditionRepository; - @Autowired private ActorResourceStateRepository actorResourceStateRepository; - @Autowired private QuarantinedActorRetentionRepository quarantinedActorRetentionRepository; - @Autowired private RuntimeInstanceCleanupService runtimeInstanceCleanupService; - @Autowired private ScopedCharacterResolver scopedCharacterResolver; - @Autowired private CharacterService characterService; - @Autowired private JdbcTemplate jdbcTemplate; - - @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; - - @BeforeEach - void clearServiceSchema() { - jdbcTemplate.execute( - "TRUNCATE TABLE entity_mutation_effects, item_transfer_audits, actor_active_conditions, " - + "actor_resource_states, character_friend, character_equipment, inventory, item_stacks, " - + "item_instances, container_instances, room_ground_inventory, items, characters, " - + "entity_playable_state_namespace_scopes RESTART IDENTITY CASCADE"); - } - - @Test - void canonicalRosterIsExactOrderedAndExcludesLegacyQuarantine() { - insertNamespace(TENANT_UUID, NAMESPACE_UUID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - UUID first = UUID.fromString("40000000-0000-4000-8000-000000000001"); - UUID second = UUID.fromString("40000000-0000-4000-8000-000000000002"); - UUID third = UUID.fromString("40000000-0000-4000-8000-000000000003"); - long legacyId = - insertActor( - "legacy-shared", - UUID.fromString("40000000-0000-4000-8000-000000000000"), - null, - null, - null, - null, - "shared-live", - "QUARANTINED", - "OWNER_PROVENANCE_MISSING", - ACCOUNT_ID, - TENANT_ID); - - assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isEmpty(); - assertThat(characterRepository.findByIdAndTenantId(legacyId, TENANT_ID)).isEmpty(); - - insertActor( - "third", - third, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - ACCOUNT_ID, - TENANT_ID); - insertActor( - "first", - first, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - ACCOUNT_ID, - TENANT_ID); - assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .extracting(identity -> identity.characterUuid()) - .containsExactly(first, third); - insertActor( - "second", - second, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - ACCOUNT_ID, - TENANT_ID); - - var roster = - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - assertThat(roster) - .extracting(identity -> identity.characterUuid()) - .containsExactly(first, second, third); - assertThat( - actorIdentityRepository.findOwnerResolvedActor( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - first.toString())) - .get() - .extracting(identity -> identity.characterUuid()) - .isEqualTo(first); - - assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - "50000000-0000-4000-8000-000000000005", - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isEmpty(); - assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - "60000000-0000-4000-8000-000000000006", - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isEmpty(); - assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - "70000000-0000-4000-8000-000000000007", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isEmpty(); - assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .isEmpty(); - assertThat( - actorIdentityRepository.findOwnerResolvedActor( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "40000000-0000-4000-8000-000000000000")) - .isEmpty(); - - assertThatThrownBy( - () -> - actorIdentityRepository.findOwnerResolvedRoster( - null, - ACCOUNT_UUID.toString(), - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - ACCOUNT_UUID.toString(), - "not-a-uuid", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - actorIdentityRepository.findOwnerResolvedRoster( - TENANT_UUID.toString(), - "00000000-0000-0000-0000-000000000000", - NAMESPACE_UUID.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class); - - assertThatThrownBy( - () -> - insertNamespace( - TENANT_UUID, NAMESPACE_UUID, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_playable_state_namespace_scopes SET playable_state_scope = ? " - + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED.name(), - TENANT_UUID, - NAMESPACE_UUID)) - .isInstanceOf(RuntimeException.class); - } - - @Test - void namespaceIdentityAndScopeAreImmutableWithoutActorReferences() { - for (PlayableStateScope scope : - new PlayableStateScope[] { - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED - }) { - UUID tenantUuid = UUID.randomUUID(); - UUID namespaceUuid = UUID.randomUUID(); - UUID changedTenantUuid = UUID.randomUUID(); - UUID changedNamespaceUuid = UUID.randomUUID(); - PlayableStateScope changedScope = - scope == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - ? PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED - : PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - insertNamespace(tenantUuid, namespaceUuid, scope); - - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - Integer.class, - tenantUuid, - namespaceUuid)) - .isZero(); - assertThat( - jdbcTemplate.update( - "UPDATE entity_playable_state_namespace_scopes " - + "SET tenant_uuid = ?, playable_state_namespace_id = ?, playable_state_scope = ? " - + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - tenantUuid, - namespaceUuid, - scope.name(), - tenantUuid, - namespaceUuid)) - .isOne(); - - assertNamespaceIdentityUpdateRejected( - "UPDATE entity_playable_state_namespace_scopes SET tenant_uuid = ? " - + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - changedTenantUuid, - tenantUuid, - namespaceUuid); - assertNamespaceIdentityUpdateRejected( - "UPDATE entity_playable_state_namespace_scopes SET playable_state_namespace_id = ? " - + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - changedNamespaceUuid, - tenantUuid, - namespaceUuid); - assertNamespaceIdentityUpdateRejected( - "UPDATE entity_playable_state_namespace_scopes SET playable_state_scope = ? " - + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - changedScope.name(), - tenantUuid, - namespaceUuid); - - assertThat( - jdbcTemplate.queryForObject( - "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes " - + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", - String.class, - tenantUuid, - namespaceUuid)) - .isEqualTo(scope.name()); - } - } - - @Test - void quarantinedActorLookupMutationExpiryAndCleanupRemainHeld() { - Character actor = new Character(); - actor.setTenantId(TENANT_ID); - actor.setAccountId(ACCOUNT_ID); - actor.setPlayableStateKey("instance:" + INSTANCE_ID); - actor.setName("Retained actor"); - actor.setExperience(17); - actor = characterRepository.save(actor); - long actorId = actor.getId(); - assertThat(actor.getActorIdentity().status().name()).isEqualTo("QUARANTINED"); - assertThat(actor.getActorIdentity().characterUuid()).isNotNull(); - assertThat(characterRepository.findById(actorId)).isEmpty(); - - ActorResourceState resourceWrite = new ActorResourceState(); - resourceWrite.setTenantId(TENANT_ID); - resourceWrite.setCharacterId(actorId); - resourceWrite.setPlayableStateKey("instance:" + INSTANCE_ID); - resourceWrite.setStatKey("health"); - resourceWrite.setCurrentValue(31L); - assertThatThrownBy(() -> actorResourceStateRepository.save(resourceWrite)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - - ActorActiveCondition conditionWrite = new ActorActiveCondition(); - conditionWrite.setTenantId(TENANT_ID); - conditionWrite.setCharacterId(actorId); - conditionWrite.setPlayableStateKey("instance:" + INSTANCE_ID); - conditionWrite.setConditionKey("stunned"); - conditionWrite.setSourceType("TEST"); - assertThatThrownBy(() -> actorActiveConditionRepository.save(conditionWrite)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - - jdbcTemplate.update( - "INSERT INTO items (id, name, tenant_id, is_container) VALUES " - + "(3001, 'Backpack', ?, true), (3002, 'Pouch', ?, true), (3003, 'Gem', ?, false)", - TENANT_ID, - TENANT_ID, - TENANT_ID); - jdbcTemplate.update( - "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (?, 3003, 5, 2)", - actorId); - jdbcTemplate.update( - "INSERT INTO character_equipment (character_id, slot, item_id, version) " - + "VALUES (?, 'hand', 3003, 3)", - actorId); - jdbcTemplate.update( - "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) " - + "VALUES (?, ?, ?, 'pending')", - actorId, - actorId, - TENANT_ID); - jdbcTemplate.update( - "INSERT INTO actor_resource_states " - + "(tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) " - + "VALUES (?, ?, 'health', 31, 90, 40, 'LEGACY_SOURCE', 'source-17', ?, 4)", - TENANT_ID, - actorId, - "instance:" + INSTANCE_ID); - jdbcTemplate.update( - "INSERT INTO actor_active_conditions " - + "(tenant_id, character_id, condition_key, stack_count, source_type, source_id, started_at, expires_at, effect_payload_json, playable_state_key, version) " - + "VALUES (?, ?, 'stunned', 3, 'LEGACY_SOURCE', 'condition-19', '2020-01-01T00:00:00Z', '2020-01-02T00:00:00Z', '{\"modifier\":2}', ?, 5)", - TENANT_ID, - actorId, - "instance:" + INSTANCE_ID); - - jdbcTemplate.update( - "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) " - + "VALUES (3101, ?, ?, ?, 3001, 6)", - TENANT_ID, - actorId, - INSTANCE_ID); - insertItemInstance(3201, actorId, INSTANCE_ID, null, 3001, "retained-backpack"); - jdbcTemplate.update("UPDATE container_instances SET item_instance_id = 3201 WHERE id = 3101"); - insertItemInstance(3202, null, INSTANCE_ID, 3101L, 3002, "retained-pouch"); - jdbcTemplate.update( - "INSERT INTO container_instances (id, tenant_id, game_instance_id, item_id, version, item_instance_id) " - + "VALUES (3102, ?, ?, 3002, 7, 3202)", - TENANT_ID, - INSTANCE_ID); - insertItemInstance(3203, null, INSTANCE_ID, 3102L, 3003, "retained-gem"); - jdbcTemplate.update( - "INSERT INTO item_stacks (id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) " - + "VALUES (3301, ?, ?, ?, 3003, 'actor-stack', 8, 2, 'actor-family')", - TENANT_ID, - actorId, - INSTANCE_ID); - jdbcTemplate.update( - "INSERT INTO item_stacks (id, tenant_id, game_instance_id, container_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) " - + "VALUES (3302, ?, ?, 3102, 3003, 'nested-stack', 9, 3, 'nested-family')", - TENANT_ID, - INSTANCE_ID); - jdbcTemplate.update( - "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " - + "VALUES (?, ?, 'room-retained', 3003, 11, 8)", - TENANT_ID, - INSTANCE_ID); - jdbcTemplate.update( - "INSERT INTO item_transfer_audits " - + "(id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) " - + "VALUES (3401, ?, 3001, 3201, 1, 'DROP', ?, 'effect-retained', 'corr-retained', 'CHARACTER', ?, ?, 'ROOM', ?, 'room-retained')", - TENANT_ID, - actorId, - actorId, - INSTANCE_ID, - INSTANCE_ID); - jdbcTemplate.update( - "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) " - + "VALUES (3501, ?, 'effect-retained', 'DROP', 'DropResponse', decode('aabb', 'hex'), 'APPLIED')", - TENANT_ID); - - assertThatThrownBy( - () -> - scopedCharacterResolver.requireScopedCharacter( - TENANT_ID, - actorId, - INSTANCE_ID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); - assertThatThrownBy( - () -> - characterService.gainExperience( - TENANT_ID, - actorId, - INSTANCE_ID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, - 100)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - runtimeInstanceCleanupService.cleanupRuntimeInstance( - TENANT_ID, INSTANCE_ID, "termination-retained")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); - - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - TENANT_ID, INSTANCE_ID)) - .isTrue(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM entity_quarantined_actor_item_instances WHERE tenant_id = ?", - Integer.class, - TENANT_ID)) - .isEqualTo(3); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM entity_quarantined_actor_container_instances WHERE tenant_id = ?", - Integer.class, - TENANT_ID)) - .isEqualTo(2); - assertThat(actorActiveConditionRepository.deleteExpired(Instant.parse("2030-01-01T00:00:00Z"))) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT experience FROM characters WHERE id = ?", Integer.class, actorId)) - .isEqualTo(17); - assertThat( - jdbcTemplate.queryForObject( - "SELECT quantity FROM inventory WHERE character_id = ? AND item_id = 3003", - Integer.class, - actorId)) - .isEqualTo(5); - assertThat( - jdbcTemplate.queryForObject( - "SELECT version FROM character_equipment WHERE character_id = ? AND slot = 'hand'", - Integer.class, - actorId)) - .isEqualTo(3); - assertThat( - jdbcTemplate.queryForObject( - "SELECT status FROM character_friend WHERE character_id = ? AND friend_id = ?", - String.class, - actorId, - actorId)) - .isEqualTo("pending"); - assertThat( - jdbcTemplate.queryForObject( - "SELECT current_value FROM actor_resource_states WHERE character_id = ? AND stat_key = 'health'", - Long.class, - actorId)) - .isEqualTo(31L); - assertThat( - jdbcTemplate.queryForObject( - "SELECT effect_payload_json FROM actor_active_conditions WHERE character_id = ?", - String.class, - actorId)) - .isEqualTo("{\"modifier\":2}"); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_instances WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - INSTANCE_ID)) - .isEqualTo(3); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - INSTANCE_ID)) - .isEqualTo(2); - assertThat( - jdbcTemplate.queryForObject( - "SELECT sum(quantity) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - INSTANCE_ID)) - .isEqualTo(17); - assertThat( - jdbcTemplate.queryForObject( - "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - INSTANCE_ID)) - .isEqualTo(11); - assertThat( - jdbcTemplate.queryForObject( - "SELECT correlation_key FROM item_transfer_audits WHERE id = 3401", String.class)) - .isEqualTo("corr-retained"); - assertThat( - jdbcTemplate.queryForObject( - "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = 3501", - String.class)) - .isEqualTo("aabb"); - } - - @Test - void destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows() { - String auditOnlyInstance = "GI-RETAINED-AUDIT-ONLY"; - long quarantinedActorId = - insertActor( - "legacy audit destination", - UUID.fromString("42000000-0000-4000-8000-000000000001"), - null, - null, - null, - null, - "shared-live", - "QUARANTINED", - "OWNER_PROVENANCE_MISSING", - ACCOUNT_ID, - TENANT_ID); - jdbcTemplate.update( - "INSERT INTO item_transfer_audits " - + "(id, tenant_id, item_id, quantity, verb, effect_id, correlation_key, source_holder_kind, source_game_instance_id, destination_holder_kind, destination_character_id, destination_game_instance_id) " - + "VALUES (3601, ?, 3001, 1, 'TAKE', 'effect-audit-only-quarantined', 'corr-audit-only-quarantined', 'ROOM', ?, 'CHARACTER', ?, ?)", - TENANT_ID, - auditOnlyInstance, - quarantinedActorId, - auditOnlyInstance); - - assertNoRuntimeRowsForInstance(auditOnlyInstance); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE id = 3601 AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", - Integer.class, - quarantinedActorId)) - .isEqualTo(1); - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - TENANT_ID, auditOnlyInstance)) - .isTrue(); - assertThatThrownBy( - () -> - runtimeInstanceCleanupService.cleanupRuntimeInstance( - TENANT_ID, auditOnlyInstance, "termination-audit-only-quarantined")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); - - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE id = 3601 AND tenant_id = ? AND correlation_key = 'corr-audit-only-quarantined' AND destination_character_id = ?", - Integer.class, - TENANT_ID, - quarantinedActorId)) - .isEqualTo(1); - assertNoRuntimeRowsForInstance(auditOnlyInstance); - } - - @Test - void destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows() { - String auditOnlyInstance = "GI-RETAINED-AUDIT-OWNER-RESOLVED"; - insertNamespace( - UUID.fromString("43000000-0000-4000-8000-000000000003"), - UUID.fromString("43000000-0000-4000-8000-000000000004"), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - long ownerResolvedActorId = - insertActor( - "owner-resolved audit destination fixture", - UUID.fromString("43000000-0000-4000-8000-000000000001"), - UUID.fromString("43000000-0000-4000-8000-000000000002"), - UUID.fromString("43000000-0000-4000-8000-000000000003"), - UUID.fromString("43000000-0000-4000-8000-000000000004"), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - ACCOUNT_ID, - TENANT_ID); - jdbcTemplate.update( - "INSERT INTO item_transfer_audits " - + "(id, tenant_id, item_id, quantity, verb, effect_id, correlation_key, source_holder_kind, source_game_instance_id, destination_holder_kind, destination_character_id, destination_game_instance_id) " - + "VALUES (3602, ?, 3001, 1, 'TAKE', 'effect-audit-only-owner-resolved', 'corr-audit-only-owner-resolved', 'ROOM', ?, 'CHARACTER', ?, ?)", - TENANT_ID, - auditOnlyInstance, - ownerResolvedActorId, - auditOnlyInstance); - - assertNoRuntimeRowsForInstance(auditOnlyInstance); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE id = 3602 AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", - Integer.class, - ownerResolvedActorId)) - .isEqualTo(1); - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - TENANT_ID, auditOnlyInstance)) - .isFalse(); - var result = - runtimeInstanceCleanupService.cleanupRuntimeInstance( - TENANT_ID, auditOnlyInstance, "termination-audit-only-owner-resolved"); - assertThat(result).isNotNull(); - assertThat(result.deletedItemInstances()).isZero(); - assertThat(result.deletedContainerInstances()).isZero(); - assertThat(result.deletedItemStacks()).isZero(); - assertThat(result.deletedRoomGroundEntries()).isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE id = 3602 AND tenant_id = ? AND correlation_key = 'corr-audit-only-owner-resolved' AND destination_character_id = ?", - Integer.class, - TENANT_ID, - ownerResolvedActorId)) - .isEqualTo(1); - assertNoRuntimeRowsForInstance(auditOnlyInstance); - } - - private void assertNoRuntimeRowsForInstance(String gameInstanceId) { - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_instances WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - gameInstanceId)) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - gameInstanceId)) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - gameInstanceId)) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - gameInstanceId)) - .isZero(); - } - - @Test - void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { - insertActor( - "legacy shared actor", - UUID.fromString("41000000-0000-4000-8000-000000000001"), - null, - null, - null, - null, - "shared-live", - "QUARANTINED", - "OWNER_PROVENANCE_MISSING", - ACCOUNT_ID, - TENANT_ID); - jdbcTemplate.update( - "INSERT INTO items (id, name, tenant_id, is_container) VALUES (3901, 'Unresolved ground item', ?, false)", - TENANT_ID); - jdbcTemplate.update( - "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " - + "VALUES (?, ?, 'room-unresolved', 3901, 2, 1)", - TENANT_ID, - INSTANCE_ID); - - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - TENANT_ID, INSTANCE_ID)) - .isTrue(); - assertThatThrownBy( - () -> - runtimeInstanceCleanupService.cleanupRuntimeInstance( - TENANT_ID, INSTANCE_ID, "termination-unresolved-ground")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); - assertThat( - jdbcTemplate.queryForObject( - "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - TENANT_ID, - INSTANCE_ID)) - .isEqualTo(2); - } - - @Test - @Timeout(value = 3, unit = TimeUnit.MINUTES) - void flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLException { - migrateLegacySchemaToV1(); - try (Connection connection = connectToMigrationSchema()) { - var statement = connection.createStatement(); - statement.executeUpdate( - "INSERT INTO characters (id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key) " - + "VALUES (101, 81, 'Legacy Shared', 71, 'shared-live', 9, 17, 21, 22, 23, 24, 31, 32, 12, 'LEGACY_BODY'), " - + "(102, 81, 'Legacy Instance', 71, 'instance:44', 3, 7, 11, 12, 13, 14, 15, 16, 5, 'LEGACY_BODY')"); - statement.executeUpdate( - "INSERT INTO items (id, name, tenant_id, is_container) VALUES (201, 'Bag', 71, true), (202, 'Gem', 71, false)"); - statement.executeUpdate( - "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (101, 202, 6, 3)"); - statement.executeUpdate( - "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) VALUES (101, 102, 71, 'pending')"); - statement.executeUpdate( - "INSERT INTO character_equipment (character_id, slot, item_id, version) VALUES (101, 'hand', 202, 4)"); - statement.executeUpdate( - "INSERT INTO actor_resource_states (id, tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) VALUES (301, 71, 101, 'health', 31, 90, 40, 'LEGACY_SOURCE', 'resource-source', 'shared-live', 8)"); - statement.executeUpdate( - "INSERT INTO actor_active_conditions (id, tenant_id, character_id, condition_key, stack_count, source_type, source_id, started_at, expires_at, effect_payload_json, playable_state_key, version) VALUES (302, 71, 101, 'stunned', 3, 'LEGACY_SOURCE', 'condition-source', '2020-01-01T00:00:00Z', '2020-01-02T00:00:00Z', '{\"modifier\":2}', 'shared-live', 9)"); - statement.executeUpdate( - "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) VALUES (401, 71, 101, '44', 201, 10)"); - statement.executeUpdate( - "INSERT INTO item_instances (id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) VALUES (501, 71, 101, '44', NULL, 201, 'legacy', 1, 'legacy-bag', 11)"); - statement.executeUpdate( - "UPDATE container_instances SET item_instance_id = 501 WHERE id = 401"); - statement.executeUpdate( - "INSERT INTO item_instances (id, tenant_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) VALUES (502, 71, '44', 401, 202, 'legacy', 2, 'legacy-gem', 12)"); - statement.executeUpdate( - "INSERT INTO item_stacks (id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) VALUES (601, 71, 101, '44', 202, 'legacy-fingerprint', 13, 14, 'legacy-family')"); - statement.executeUpdate( - "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) VALUES (71, '44', 'room-9', 202, 15, 16)"); - statement.executeUpdate( - "INSERT INTO item_transfer_audits (id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) VALUES (701, 71, 202, 502, 2, 'DROP', 101, 'legacy-effect', 'legacy-correlation', 'CHARACTER', 101, '44', 'ROOM', '44', 'room-9')"); - statement.executeUpdate( - "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) VALUES (801, 71, 'legacy-effect', 'DROP', 'DropResponse', decode('cafe', 'hex'), 'APPLIED')"); - statement.close(); - } - - migrateLegacySchemaToLatest(); - - try (Connection connection = connectToMigrationSchema(); - var statement = connection.createStatement()) { - assertThat( - readLong( - statement, - "SELECT count(*) FROM pg_constraint " - + "WHERE conrelid = 'characters'::regclass AND convalidated " - + "AND conname IN ('ck_characters_actor_identity_status', " - + "'ck_characters_actor_identity_quarantine_reason', " - + "'ck_characters_actor_identity_uuid_non_nil', " - + "'ck_characters_actor_identity_scope', " - + "'ck_characters_owner_resolved_provenance', " - + "'fk_characters_owner_resolved_namespace_scope', " - + "'ck_characters_character_uuid_non_nil', " - + "'ux_characters_character_uuid')")) - .isEqualTo(8L); - assertThat( - readLong( - statement, - "SELECT count(*) FROM pg_index indexes " - + "JOIN pg_class index_relation ON index_relation.oid = indexes.indexrelid " - + "JOIN pg_namespace index_schema ON index_schema.oid = index_relation.relnamespace " - + "WHERE index_schema.nspname = current_schema() " - + "AND index_relation.relname IN ('ux_characters_character_uuid', " - + "'idx_characters_owner_resolved_roster') " - + "AND indexes.indisvalid AND indexes.indisready")) - .isEqualTo(2L); - assertThat( - readLong( - statement, - "SELECT count(*) FROM pg_attribute " - + "WHERE attrelid = 'characters'::regclass AND attname = 'character_uuid' " - + "AND attnotnull AND NOT attisdropped")) - .isEqualTo(1L); - try (var rows = - statement.executeQuery( - "SELECT id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason FROM characters ORDER BY id")) { - assertThat(rows.next()).isTrue(); - UUID firstActorUuid = rows.getObject("character_uuid", UUID.class); - assertThat(firstActorUuid).isNotNull().isNotEqualTo(new UUID(0L, 0L)); - assertThat(rows.getLong("id")).isEqualTo(101L); - assertThat(rows.getLong("account_id")).isEqualTo(81L); - assertThat(rows.getString("name")).isEqualTo("Legacy Shared"); - assertThat(rows.getLong("tenant_id")).isEqualTo(71L); - assertThat(rows.getString("playable_state_key")).isEqualTo("shared-live"); - assertThat(rows.getInt("level")).isEqualTo(9); - assertThat(rows.getInt("experience")).isEqualTo(17); - assertThat(rows.getInt("strength")).isEqualTo(21); - assertThat(rows.getInt("agility")).isEqualTo(22); - assertThat(rows.getInt("intelligence")).isEqualTo(23); - assertThat(rows.getInt("stamina")).isEqualTo(24); - assertThat(rows.getInt("health")).isEqualTo(31); - assertThat(rows.getInt("mana")).isEqualTo(32); - assertThat(rows.getInt("version")).isEqualTo(12); - assertThat(rows.getString("body_layout_key")).isEqualTo("LEGACY_BODY"); - assertThat(rows.getObject("account_uuid")).isNull(); - assertThat(rows.getObject("tenant_uuid")).isNull(); - assertThat(rows.getObject("playable_state_namespace_id")).isNull(); - assertThat(rows.getString("playable_state_scope")).isNull(); - assertThat(rows.getString("actor_identity_status")).isEqualTo("QUARANTINED"); - assertThat(rows.getString("actor_identity_quarantine_reason")) - .isEqualTo("OWNER_PROVENANCE_MISSING"); - assertThat(rows.next()).isTrue(); - UUID secondActorUuid = rows.getObject("character_uuid", UUID.class); - assertThat(secondActorUuid).isNotNull().isNotEqualTo(firstActorUuid); - assertThat(rows.getLong("id")).isEqualTo(102L); - assertThat(rows.getLong("account_id")).isEqualTo(81L); - assertThat(rows.getLong("tenant_id")).isEqualTo(71L); - assertThat(rows.getString("playable_state_key")).isEqualTo("instance:44"); - assertThat(rows.getString("actor_identity_status")).isEqualTo("QUARANTINED"); - assertThat(rows.getObject("account_uuid")).isNull(); - assertThat(rows.getObject("playable_state_namespace_id")).isNull(); - assertThat(rows.next()).isFalse(); - } - assertThat( - readLong( - statement, - "SELECT quantity FROM inventory WHERE character_id = 101 AND item_id = 202")) - .isEqualTo(6L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', character_id, item_id, quantity, version) FROM inventory WHERE character_id = 101 AND item_id = 202")) - .isEqualTo("101|202|6|3"); - assertThat( - readString(statement, "SELECT status FROM character_friend WHERE character_id = 101")) - .isEqualTo("pending"); - assertThat( - readString( - statement, - "SELECT concat_ws('|', character_id, friend_id, tenant_id, status) FROM character_friend WHERE character_id = 101")) - .isEqualTo("101|102|71|pending"); - assertThat( - readLong( - statement, "SELECT version FROM character_equipment WHERE character_id = 101")) - .isEqualTo(4L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', character_id, slot, item_id, version) FROM character_equipment WHERE character_id = 101")) - .isEqualTo("101|hand|202|4"); - assertThat( - readLong(statement, "SELECT current_value FROM actor_resource_states WHERE id = 301")) - .isEqualTo(31L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) FROM actor_resource_states WHERE id = 301")) - .isEqualTo("301|71|101|health|31|90|40|LEGACY_SOURCE|resource-source|shared-live|8"); - assertThat( - readString( - statement, - "SELECT effect_payload_json FROM actor_active_conditions WHERE id = 302")) - .isEqualTo("{\"modifier\":2}"); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, character_id, condition_key, stack_count, source_type, source_id, playable_state_key, version) FROM actor_active_conditions WHERE id = 302")) - .isEqualTo("302|71|101|stunned|3|LEGACY_SOURCE|condition-source|shared-live|9"); - assertThat( - readLong( - statement, - "SELECT extract(epoch FROM started_at)::bigint FROM actor_active_conditions WHERE id = 302")) - .isEqualTo(1577836800L); - assertThat( - readLong( - statement, - "SELECT extract(epoch FROM expires_at)::bigint FROM actor_active_conditions WHERE id = 302")) - .isEqualTo(1577923200L); - assertThat(readLong(statement, "SELECT count(*) FROM item_instances WHERE id IN (501, 502)")) - .isEqualTo(2L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) FROM item_instances WHERE id = 501")) - .isEqualTo("501|71|101|44|201|legacy|1|legacy-bag|11"); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) FROM item_instances WHERE id = 502")) - .isEqualTo("502|71|44|401|202|legacy|2|legacy-gem|12"); - assertThat( - readLong( - statement, "SELECT container_instance_id FROM item_instances WHERE id = 502")) - .isEqualTo(401L); - assertThat( - readLong( - statement, "SELECT item_instance_id FROM container_instances WHERE id = 401")) - .isEqualTo(501L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, item_id, item_instance_id, version) FROM container_instances WHERE id = 401")) - .isEqualTo("401|71|101|44|201|501|10"); - assertThat(readLong(statement, "SELECT quantity FROM item_stacks WHERE id = 601")) - .isEqualTo(13L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) FROM item_stacks WHERE id = 601")) - .isEqualTo("601|71|101|44|202|legacy-fingerprint|13|14|legacy-family"); - assertThat( - readLong( - statement, - "SELECT quantity FROM room_ground_inventory WHERE room_instance_id = 'room-9'")) - .isEqualTo(15L); - assertThat( - readString( - statement, - "SELECT concat_ws('|', tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) FROM room_ground_inventory WHERE room_instance_id = 'room-9'")) - .isEqualTo("71|44|room-9|202|15|16"); - assertThat( - readString( - statement, "SELECT correlation_key FROM item_transfer_audits WHERE id = 701")) - .isEqualTo("legacy-correlation"); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) FROM item_transfer_audits WHERE id = 701")) - .isEqualTo( - "701|71|202|502|2|DROP|101|legacy-effect|legacy-correlation|CHARACTER|101|44|ROOM|44|room-9"); - assertThat( - readString( - statement, - "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = 801")) - .isEqualTo("cafe"); - assertThat( - readString( - statement, - "SELECT concat_ws('|', id, tenant_id, effect_id, operation_name, response_type, encode(response_payload, 'hex'), status) FROM entity_mutation_effects WHERE id = 801")) - .isEqualTo("801|71|legacy-effect|DROP|DropResponse|cafe|APPLIED"); - } - } - - private void insertNamespace(UUID tenantUuid, UUID namespaceUuid, PlayableStateScope scope) { - jdbcTemplate.update( - "INSERT INTO entity_playable_state_namespace_scopes " - + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?)", - tenantUuid, - namespaceUuid, - scope.name()); - } - - private void assertNamespaceIdentityUpdateRejected(String sql, Object... arguments) { - assertThatThrownBy(() -> jdbcTemplate.update(sql, arguments)) - .hasMessageContaining("entity playable-state namespace identity is immutable"); - } - - @Test - void characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch() { - UUID characterUuid = UUID.fromString("40000000-0000-4000-8000-000000000010"); - insertNamespace(TENANT_UUID, NAMESPACE_UUID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - long actorId = - insertActor( - "Tenant-owned actor", - characterUuid, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - ACCOUNT_ID, - TENANT_ID); - - Character crossTenantUpdate = - characterRepository.findByIdAndTenantId(actorId, TENANT_ID).orElseThrow(); - int originalVersion = crossTenantUpdate.getVersion(); - int originalExperience = crossTenantUpdate.getExperience(); - crossTenantUpdate.setTenantId(TENANT_ID + 1); - crossTenantUpdate.setName("Cross-tenant overwrite"); - crossTenantUpdate.setExperience(originalExperience + 99); - - assertThatThrownBy(() -> characterRepository.save(crossTenantUpdate)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("CHARACTER_IDENTITY_NOT_OWNER_RESOLVED"); - - Character unchanged = characterRepository.findByIdAndTenantId(actorId, TENANT_ID).orElseThrow(); - assertThat(unchanged.getTenantId()).isEqualTo(TENANT_ID); - assertThat(unchanged.getName()).isEqualTo("Tenant-owned actor"); - assertThat(unchanged.getExperience()).isEqualTo(originalExperience); - assertThat(unchanged.getVersion()).isEqualTo(originalVersion); - - Character validUpdate = - characterRepository.findByIdAndTenantId(actorId, TENANT_ID).orElseThrow(); - validUpdate.setName("Tenant-owned actor updated"); - Character saved = characterRepository.save(validUpdate); - assertThat(saved.getTenantId()).isEqualTo(TENANT_ID); - assertThat(saved.getName()).isEqualTo("Tenant-owned actor updated"); - assertThat(saved.getVersion()).isEqualTo(originalVersion + 1); - } - - private long insertActor( - String name, - UUID characterUuid, - UUID accountUuid, - UUID tenantUuid, - UUID namespaceUuid, - PlayableStateScope scope, - String legacyStateKey, - String status, - String quarantineReason, - long legacyAccountId, - long legacyTenantId) { - Long actorId = - jdbcTemplate.queryForObject( - "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", - Long.class, - legacyAccountId, - name, - legacyTenantId, - legacyStateKey, - characterUuid, - accountUuid, - tenantUuid, - namespaceUuid, - scope == null ? null : scope.name(), - status, - quarantineReason); - return Objects.requireNonNull( - actorId, "Character INSERT ... RETURNING id must return the inserted actor ID"); - } - - private void insertItemInstance( - long id, - Long characterId, - String gameInstanceId, - Long containerId, - long itemId, - String visibleRef) { - jdbcTemplate.update( - "INSERT INTO item_instances (id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)", - id, - TENANT_ID, - characterId, - gameInstanceId, - containerId, - itemId, - "retained", - id, - visibleRef); - } - - private void migrateLegacySchemaToV1() throws SQLException { - migrationSchema = "retained_actor_v1_to_v2_" + UUID.randomUUID().toString().replace("-", ""); - try (Connection connection = - DriverManager.getConnection( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); - var statement = connection.createStatement()) { - statement.execute("CREATE SCHEMA " + migrationSchema); - } - migrationFlyway().target(MigrationVersion.fromVersion("1")).load().migrate(); - } - - private void migrateLegacySchemaToLatest() { - migrationFlyway().load().migrate(); - } - - private FluentConfiguration migrationFlyway() { - FluentConfiguration configuration = - Flyway.configure() - .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) - .schemas(migrationSchema) - .defaultSchema(migrationSchema) - .locations("classpath:db/migration") - .placeholders(Map.of("serviceSchema", migrationSchema)); - configuration - .getConfigurationExtension(PostgreSQLConfigurationExtension.class) - .setTransactionalLock(false); - return configuration.jdbcProperties( - Map.of("options", "-c lock_timeout=30s -c statement_timeout=120s")); - } - - private Connection connectToMigrationSchema() throws SQLException { - Connection connection = - DriverManager.getConnection( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); - try (var statement = connection.createStatement()) { - statement.execute("SET search_path TO " + migrationSchema); - } - return connection; - } - - private long readLong(java.sql.Statement statement, String sql) throws SQLException { - try (var rows = statement.executeQuery(sql)) { - assertThat(rows.next()).isTrue(); - return rows.getLong(1); - } - } - - private String readString(java.sql.Statement statement, String sql) throws SQLException { - try (var rows = statement.executeQuery(sql)) { - assertThat(rows.next()).isTrue(); - return rows.getString(1); - } - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java deleted file mode 100644 index 6f3995a989..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.firedevops.firemud.entitymanagement; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.env.YamlPropertySourceLoader; -import org.springframework.boot.flyway.autoconfigure.FlywayProperties; -import org.springframework.core.env.StandardEnvironment; -import org.springframework.core.io.FileSystemResource; - -class FlywayPostgresqlLockConfigurationTest { - @Test - void identityValidationScansFinishBeforeStrongLockFinalization() throws IOException { - String migration = - Files.readString( - Path.of("src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql")); - int lastValidation = migration.lastIndexOf("VALIDATE CONSTRAINT "); - int setNotNull = migration.indexOf("ALTER COLUMN character_uuid SET NOT NULL"); - int dropProofCheck = migration.indexOf("DROP CONSTRAINT ck_characters_character_uuid_nonnull"); - - assertThat(lastValidation).isGreaterThanOrEqualTo(0); - assertThat(setNotNull).isGreaterThan(lastValidation); - assertThat(dropProofCheck).isGreaterThan(setNotNull); - assertThat(migration).contains("VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull"); - } - - @Test - void allServiceProfilesBindSessionLevelPostgresqlAdvisoryLocks() throws IOException { - for (Path resourcePath : - List.of( - Path.of("src/main/resources/application.yml"), - Path.of("src/main/resources/application-prod.yml"), - Path.of("src/test/resources/application.yml"))) { - var propertySource = - new YamlPropertySourceLoader() - .load(resourcePath.toString(), new FileSystemResource(resourcePath.toFile())) - .getFirst(); - var environment = new StandardEnvironment(); - environment.getPropertySources().addFirst(propertySource); - - FlywayProperties properties = - Binder.get(environment) - .bind("spring.flyway", FlywayProperties.class) - .orElseThrow( - () -> new AssertionError("Flyway settings did not bind from " + resourcePath)); - - assertThat(properties.getPostgresql().getTransactionalLock()) - .as("PostgreSQL transactional advisory locks in %s", resourcePath) - .isFalse(); - } - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java deleted file mode 100644 index e4ec45fe07..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package net.firedevops.firemud.entitymanagement.entity; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.UUID; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import org.junit.jupiter.api.Test; - -class ActorIdentityValueTest { - private static final UUID ACTOR_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID ACCOUNT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); - private static final UUID TENANT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); - private static final UUID NAMESPACE_UUID = - UUID.fromString("44444444-4444-4444-8444-444444444444"); - - @Test - void parsesOnlyCompleteNonNilUuidValues() { - assertEquals(ACTOR_UUID, ActorIdentity.parseRequiredUuid(ACTOR_UUID.toString(), "actor")); - assertThrows( - IllegalArgumentException.class, () -> ActorIdentity.parseRequiredUuid(null, "actor")); - assertThrows( - IllegalArgumentException.class, - () -> ActorIdentity.parseRequiredUuid("not-a-uuid", "actor")); - assertThrows( - IllegalArgumentException.class, - () -> ActorIdentity.parseRequiredUuid("00000000-0000-0000-0000-000000000000", "actor")); - } - - @Test - void ownerResolvedIdentityRequiresExactAccountTenantNamespaceAndScope() { - var identity = - new ActorIdentity( - ACTOR_UUID, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - ActorIdentityStatus.OWNER_RESOLVED, - null); - assertEquals(ActorIdentityStatus.OWNER_RESOLVED, identity.status()); - - assertThrows( - IllegalArgumentException.class, - () -> - new ActorIdentity( - ACTOR_UUID, - null, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - ActorIdentityStatus.OWNER_RESOLVED, - null)); - assertThrows( - IllegalArgumentException.class, - () -> - new ActorIdentity( - ACTOR_UUID, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, - ActorIdentityStatus.OWNER_RESOLVED, - null)); - assertThrows( - IllegalArgumentException.class, - () -> - new ActorIdentity( - ACTOR_UUID, - ACCOUNT_UUID, - TENANT_UUID, - NAMESPACE_UUID, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - ActorIdentityStatus.OWNER_RESOLVED, - "LEGACY_IDENTITY")); - } - - @Test - void quarantineCanRetainIncompleteSourceProvenanceWithoutCreatingAnAlias() { - var quarantined = - new ActorIdentity( - ACTOR_UUID, - null, - null, - null, - null, - ActorIdentityStatus.QUARANTINED, - "OWNER_PROVENANCE_MISSING"); - assertEquals(ActorIdentityStatus.QUARANTINED, quarantined.status()); - - assertThrows( - IllegalArgumentException.class, - () -> - new ActorIdentity( - new UUID(0L, 0L), - null, - null, - null, - null, - ActorIdentityStatus.QUARANTINED, - "OWNER_PROVENANCE_MISSING")); - assertThrows( - IllegalArgumentException.class, - () -> - new ActorIdentity( - ACTOR_UUID, ACCOUNT_UUID, null, null, null, ActorIdentityStatus.QUARANTINED, " ")); - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java deleted file mode 100644 index 1259a124fd..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.firedevops.firemud.entitymanagement.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.Arrays; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Result; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.jooq.tools.jdbc.MockConnection; -import org.jooq.tools.jdbc.MockDataProvider; -import org.jooq.tools.jdbc.MockResult; -import org.junit.jupiter.api.Test; - -class ActorActiveConditionRepositoryTest { - private static final Long ROW_ID = 71L; - private static final Long TENANT_ID = 13L; - private static final String PLAYABLE_STATE_KEY = "world:scope:4"; - private static final Long CHARACTER_ID = 29L; - - @Test - void saveUpdateUsesPersistedIdentityPredicatesAndOwnerResolvedGuard() { - AtomicReference updateSql = new AtomicReference<>(); - AtomicReference updateBindings = new AtomicReference<>(); - MockDataProvider provider = providerForUpdate(1, updateSql, updateBindings); - ActorActiveConditionRepository repository = repository(provider); - var entity = condition(); - - repository.save(entity); - - String sql = updateSql.get().toLowerCase(Locale.ROOT); - String whereClause = sql.substring(sql.indexOf(" where ")).replaceAll("\\s+", " "); - assertThat(whereClause) - .contains( - "\"id\" = ?", - "\"tenant_id\" = ?", - "\"playable_state_key\" = ?", - "\"character_id\" = ?", - "exists (select 1", - "\"actor_identity_status\" = ?"); - assertThat(Arrays.asList(updateBindings.get())) - .contains(ROW_ID, TENANT_ID, PLAYABLE_STATE_KEY, CHARACTER_ID, "OWNER_RESOLVED"); - assertThat(entity.getVersion()).isEqualTo(5); - } - - @Test - void saveUpdateWithZeroRowsFailsWithoutChangingVersion() { - ActorActiveCondition entity = condition(); - assertUpdateFailure(entity, 0); - } - - @Test - void saveUpdateWithMultipleRowsFailsWithoutChangingVersion() { - ActorActiveCondition entity = condition(); - assertUpdateFailure(entity, 2); - } - - private static void assertUpdateFailure(ActorActiveCondition entity, int updatedRows) { - ActorActiveConditionRepository repository = - repository( - providerForUpdate(updatedRows, new AtomicReference<>(), new AtomicReference<>())); - - assertThatThrownBy(() -> repository.save(entity)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - assertThat(entity.getVersion()).isEqualTo(4); - } - - private static MockDataProvider providerForUpdate( - int updatedRows, - AtomicReference updateSql, - AtomicReference updateBindings) { - DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); - Field countField = DSL.field("count", Integer.class); - Record1 countRow = resultDsl.newRecord(countField); - countRow.set(countField, 1); - Result> countResult = resultDsl.newResult(countField); - countResult.add(countRow); - return context -> { - String sql = context.sql().trim(); - if (sql.toLowerCase(Locale.ROOT).startsWith("update")) { - updateSql.set(sql); - updateBindings.set(context.bindings()); - return new MockResult[] {new MockResult(updatedRows)}; - } - return new MockResult[] {new MockResult(1, countResult)}; - }; - } - - private static ActorActiveConditionRepository repository(MockDataProvider provider) { - return new ActorActiveConditionRepository( - DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); - } - - private static ActorActiveCondition condition() { - var entity = new ActorActiveCondition(); - entity.setId(ROW_ID); - entity.setTenantId(TENANT_ID); - entity.setPlayableStateKey(PLAYABLE_STATE_KEY); - entity.setCharacterId(CHARACTER_ID); - entity.setConditionKey("condition-unique"); - entity.setStackCount(3); - entity.setSourceType("source-unique"); - entity.setSourceId("source-id-unique"); - entity.setStartedAt(Instant.parse("2024-01-01T00:00:00Z")); - entity.setExpiresAt(Instant.parse("2024-01-02T00:00:00Z")); - entity.setEffectPayloadJson("{\"unique\":true}"); - entity.setCreatedAt(Instant.parse("2024-01-03T00:00:00Z")); - entity.setUpdatedAt(Instant.parse("2024-01-04T00:00:00Z")); - entity.setVersion(4); - return entity; - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java deleted file mode 100644 index 80e3187ffb..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.firedevops.firemud.entitymanagement.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.Arrays; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Result; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.jooq.tools.jdbc.MockConnection; -import org.jooq.tools.jdbc.MockDataProvider; -import org.jooq.tools.jdbc.MockResult; -import org.junit.jupiter.api.Test; - -class ActorResourceStateRepositoryTest { - private static final Long ROW_ID = 83L; - private static final Long TENANT_ID = 17L; - private static final String PLAYABLE_STATE_KEY = "realm:state:9"; - private static final Long CHARACTER_ID = 37L; - - @Test - void saveUpdateUsesPersistedIdentityPredicatesAndOwnerResolvedGuard() { - AtomicReference updateSql = new AtomicReference<>(); - AtomicReference updateBindings = new AtomicReference<>(); - ActorResourceStateRepository repository = - repository(providerForUpdate(1, updateSql, updateBindings)); - var entity = state(); - - repository.save(entity); - - String sql = updateSql.get().toLowerCase(Locale.ROOT); - String whereClause = sql.substring(sql.indexOf(" where ")).replaceAll("\\s+", " "); - assertThat(whereClause) - .contains( - "\"id\" = ?", - "\"tenant_id\" = ?", - "\"playable_state_key\" = ?", - "\"character_id\" = ?", - "exists (select 1", - "\"actor_identity_status\" = ?"); - assertThat(Arrays.asList(updateBindings.get())) - .contains(ROW_ID, TENANT_ID, PLAYABLE_STATE_KEY, CHARACTER_ID, "OWNER_RESOLVED"); - assertThat(entity.getVersion()).isEqualTo(6); - } - - @Test - void saveUpdateWithZeroRowsFailsWithoutChangingVersion() { - assertUpdateFailure(state(), 0); - } - - @Test - void saveUpdateWithMultipleRowsFailsWithoutChangingVersion() { - assertUpdateFailure(state(), 2); - } - - private static void assertUpdateFailure(ActorResourceState entity, int updatedRows) { - ActorResourceStateRepository repository = - repository( - providerForUpdate(updatedRows, new AtomicReference<>(), new AtomicReference<>())); - - assertThatThrownBy(() -> repository.save(entity)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - assertThat(entity.getVersion()).isEqualTo(5); - } - - private static MockDataProvider providerForUpdate( - int updatedRows, - AtomicReference updateSql, - AtomicReference updateBindings) { - DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); - Field countField = DSL.field("count", Integer.class); - Record1 countRow = resultDsl.newRecord(countField); - countRow.set(countField, 1); - Result> countResult = resultDsl.newResult(countField); - countResult.add(countRow); - return context -> { - String sql = context.sql().trim(); - if (sql.toLowerCase(Locale.ROOT).startsWith("update")) { - updateSql.set(sql); - updateBindings.set(context.bindings()); - return new MockResult[] {new MockResult(updatedRows)}; - } - return new MockResult[] {new MockResult(1, countResult)}; - }; - } - - private static ActorResourceStateRepository repository(MockDataProvider provider) { - return new ActorResourceStateRepository( - DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); - } - - private static ActorResourceState state() { - var entity = new ActorResourceState(); - entity.setId(ROW_ID); - entity.setTenantId(TENANT_ID); - entity.setPlayableStateKey(PLAYABLE_STATE_KEY); - entity.setCharacterId(CHARACTER_ID); - entity.setStatKey("resource-unique"); - entity.setCurrentValue(11L); - entity.setMaxValue(19L); - entity.setBaseValue(23L); - entity.setSourceType("source-unique"); - entity.setSourceId("source-id-unique"); - entity.setCreatedAt(Instant.parse("2024-02-01T00:00:00Z")); - entity.setUpdatedAt(Instant.parse("2024-02-02T00:00:00Z")); - entity.setVersion(5); - return entity; - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java deleted file mode 100644 index e0608c913d..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package net.firedevops.firemud.entitymanagement.repository; - -import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTER_FRIEND; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.Arrays; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; -import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Result; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.jooq.tools.jdbc.MockConnection; -import org.jooq.tools.jdbc.MockDataProvider; -import org.jooq.tools.jdbc.MockResult; -import org.junit.jupiter.api.Test; - -class CharacterFriendRepositoryTest { - private static final Long TENANT_ID = 17L; - private static final Long CHARACTER_ID = 37L; - private static final Long FRIEND_ID = 41L; - - @Test - void saveRejectsSelfRelationshipBeforeDatabaseInteraction() { - AtomicInteger queryCount = new AtomicInteger(); - CharacterFriendRepository repository = - repository( - context -> { - queryCount.incrementAndGet(); - throw new AssertionError( - "self relationships must be rejected before database access"); - }); - - assertThatThrownBy(() -> repository.save(friend(CHARACTER_ID, CHARACTER_ID))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("FRIEND_SELF_RELATIONSHIP_NOT_ALLOWED"); - assertThat(queryCount).hasValue(0); - } - - @Test - void saveStillRejectsDistinctPairWithoutTwoOwnerResolvedActors() { - AtomicInteger queryCount = new AtomicInteger(); - AtomicReference guardBindings = new AtomicReference<>(); - CharacterFriendRepository repository = - repository( - context -> { - queryCount.incrementAndGet(); - guardBindings.set(context.bindings()); - return ownerResolvedCountResult(1); - }); - - assertThatThrownBy(() -> repository.save(friend(CHARACTER_ID, FRIEND_ID))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("FRIEND_ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - assertThat(queryCount).hasValue(1); - assertThat(Arrays.asList(guardBindings.get())) - .contains(CHARACTER_ID, FRIEND_ID, TENANT_ID, "OWNER_RESOLVED"); - } - - @Test - void saveChecksExactTenantAndOwnerResolvedGuardForDistinctPair() { - AtomicInteger queryCount = new AtomicInteger(); - AtomicReference guardSql = new AtomicReference<>(); - AtomicReference guardBindings = new AtomicReference<>(); - CharacterFriend entity = friend(CHARACTER_ID, FRIEND_ID); - CharacterFriendRepository repository = - repository( - context -> { - queryCount.incrementAndGet(); - String sql = context.sql().trim(); - if (sql.toLowerCase(Locale.ROOT).startsWith("select count")) { - guardSql.set(sql); - guardBindings.set(context.bindings()); - return ownerResolvedCountResult(2); - } - if (sql.toLowerCase(Locale.ROOT).startsWith("select")) { - DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); - return new MockResult[] { - new MockResult(0, resultDsl.newResult(CHARACTER_FRIEND.fields())) - }; - } - if (sql.toLowerCase(Locale.ROOT).startsWith("insert")) { - return new MockResult[] {new MockResult(1)}; - } - throw new AssertionError("Unexpected database interaction: " + sql); - }); - - assertThat(repository.save(entity)).isSameAs(entity); - - String normalizedGuardSql = guardSql.get().toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); - assertThat(normalizedGuardSql) - .contains(" from \"characters\"") - .contains("\"id\" in (?, ?)") - .contains("\"tenant_id\" = ?") - .contains("\"actor_identity_status\" = ?"); - assertThat(Arrays.asList(guardBindings.get())) - .contains(CHARACTER_ID, FRIEND_ID, TENANT_ID, "OWNER_RESOLVED"); - assertThat(queryCount).hasValue(3); - } - - private static CharacterFriendRepository repository(MockDataProvider provider) { - return new CharacterFriendRepository( - DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); - } - - private static MockResult[] ownerResolvedCountResult(int count) { - DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); - Field countField = DSL.field("count", Integer.class); - Record1 countRow = resultDsl.newRecord(countField); - countRow.set(countField, count); - Result> countResult = resultDsl.newResult(countField); - countResult.add(countRow); - return new MockResult[] {new MockResult(1, countResult)}; - } - - private static CharacterFriend friend(Long characterId, Long friendId) { - CharacterFriendKey key = new CharacterFriendKey(); - key.setCharacterId(characterId); - key.setFriendId(friendId); - CharacterFriend entity = new CharacterFriend(); - entity.setId(key); - entity.setTenantId(TENANT_ID); - entity.setCreatedAt(Instant.parse("2024-01-03T00:00:00Z")); - return entity; - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java deleted file mode 100644 index f54733cc89..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.firedevops.firemud.entitymanagement.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Arrays; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicReference; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Result; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.jooq.tools.jdbc.MockConnection; -import org.jooq.tools.jdbc.MockDataProvider; -import org.jooq.tools.jdbc.MockResult; -import org.junit.jupiter.api.Test; - -class QuarantinedActorRetentionRepositoryTest { - private static final Long TENANT_ID = 29L; - private static final String GAME_INSTANCE_ID = "runtime-opaque"; - - @Test - void readsTypedBooleanWithOneTargetBindingPairAndHoldsRowsNeedingClassification() { - AtomicReference sqlRead = new AtomicReference<>(); - AtomicReference bindingsRead = new AtomicReference<>(); - QuarantinedActorRetentionRepository repository = repository(true, sqlRead, bindingsRead); - - assertThat(repository.hasUnclassifiedOrQuarantinedRuntimeEvidence(TENANT_ID, GAME_INSTANCE_ID)) - .isTrue(); - - String sql = sqlRead.get().toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); - assertThat(sql) - .contains("with target as") - .contains("cast(? as bigint)") - .contains("cast(? as text)") - .contains("from item_instances item_instance") - .contains("from container_instances container") - .contains("from item_stacks stack") - .contains("from room_ground_inventory ground") - .contains("actor.actor_identity_status = 'quarantined'") - .contains("audit.source_game_instance_id = target.game_instance_id") - .contains("audit.destination_game_instance_id = target.game_instance_id") - .contains("as boolean)"); - assertThat(Arrays.asList(bindingsRead.get())).containsExactly(TENANT_ID, GAME_INSTANCE_ID); - } - - @Test - void falseBooleanReportsNoObservedUnclassifiedOrQuarantinedEvidence() { - QuarantinedActorRetentionRepository repository = repository(false, null, null); - - assertThat(repository.hasUnclassifiedOrQuarantinedRuntimeEvidence(TENANT_ID, GAME_INSTANCE_ID)) - .isFalse(); - } - - @Test - void nullBooleanReadbackFailsClosed() { - QuarantinedActorRetentionRepository repository = repository(null, null, null); - - assertThatThrownBy( - () -> - repository.hasUnclassifiedOrQuarantinedRuntimeEvidence(TENANT_ID, GAME_INSTANCE_ID)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("RUNTIME_EVIDENCE_READBACK_UNAVAILABLE"); - } - - private static QuarantinedActorRetentionRepository repository( - Boolean readback, AtomicReference sqlRead, AtomicReference bindingsRead) { - MockDataProvider provider = - context -> { - if (sqlRead != null) { - sqlRead.set(context.sql()); - } - if (bindingsRead != null) { - bindingsRead.set(context.bindings()); - } - DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); - Field retainedField = DSL.field("retained", Boolean.class); - Record1 row = resultDsl.newRecord(retainedField); - row.set(retainedField, readback); - Result> result = resultDsl.newResult(retainedField); - result.add(row); - return new MockResult[] {new MockResult(1, result)}; - }; - return new QuarantinedActorRetentionRepository( - DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java deleted file mode 100644 index 102694fedd..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.firedevops.firemud.entitymanagement.service; - -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.Optional; -import java.util.UUID; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; -import net.firedevops.firemud.entitymanagement.entity.Character; -import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import org.junit.jupiter.api.Test; - -class ScopedCharacterResolverTest { - @Test - void rejectsLegacyScopeEvenWhenRepositoryCanReturnOwnerResolvedCandidate() { - CharacterRepository repository = mock(CharacterRepository.class); - Character candidate = new Character(); - candidate.setId(17L); - candidate.setTenantId(23L); - candidate.setActorIdentity( - new ActorIdentity( - UUID.fromString("40000000-0000-4000-8000-000000000001"), - UUID.fromString("20000000-0000-4000-8000-000000000002"), - UUID.fromString("10000000-0000-4000-8000-000000000001"), - UUID.fromString("30000000-0000-4000-8000-000000000003"), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - ActorIdentityStatus.OWNER_RESOLVED, - null)); - when(repository.findByIdAndTenantIdAndPlayableStateKey(17L, 23L, "shared-live")) - .thenReturn(Optional.of(candidate)); - - assertThat(repository.findByIdAndTenantIdAndPlayableStateKey(17L, 23L, "shared-live")) - .hasValueSatisfying(found -> assertThat(found).isSameAs(candidate)); - - ScopedCharacterResolver resolver = - new ScopedCharacterResolver(repository, new PlayableStateKeyResolver()); - assertThatThrownBy( - () -> - resolver.requireScopedCharacter( - 23L, 17L, "GI-1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); - } -} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java index 2bab84dc06..3c16b64078 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java @@ -1,8 +1,12 @@ package net.firedevops.firemud.entitymanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; @@ -11,44 +15,72 @@ import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import org.mockito.Mockito; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; class CharacterServiceImplListTest { @Test - void legacyGameplayRosterRemainsClosedWithoutOwnerResolvedIdentity() { + void listForTenantAndAccountReturnsDtos() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); + var cacheManager = new ConcurrentMapCacheManager("characterGraph"); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); CharacterServiceImpl service = new CharacterServiceImpl( repo, mapper, + cacheManager, + meterRegistry, new PlayableStateKeyResolver(), new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); + + Character c = new Character(); + c.setId(1L); + c.setTenantId(1L); + c.setAccountId(1L); + c.setPlayableStateKey("shared-live"); + c.setName("Hero"); + + when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( + 1L, 1L, "shared-live", Pageable.unpaged())) + .thenReturn(new PageImpl<>(List.of(c))); var result = service.listForGameplayScope( 1L, 1L, "44", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, Pageable.unpaged()); - assertEquals(0, result.getTotalElements()); - assertEquals(0, result.getContent().size()); - verifyNoInteractions(repo); + assertEquals(1, result.getTotalElements()); + assertEquals("Hero", result.getContent().get(0).name()); + verify(repo) + .findByTenantIdAndAccountIdAndPlayableStateKey(1L, 1L, "shared-live", Pageable.unpaged()); } @Test void listForTenantAndAccountDoesNotCrossTenantBoundary() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); + var cacheManager = new ConcurrentMapCacheManager("characterGraph"); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); CharacterServiceImpl service = new CharacterServiceImpl( repo, mapper, + cacheManager, + meterRegistry, new PlayableStateKeyResolver(), new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); + + when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( + 2L, 1L, "instance:91", Pageable.unpaged())) + .thenReturn(new PageImpl<>(List.of())); var result = service.listForGameplayScope( 2L, 1L, "91", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, Pageable.unpaged()); assertEquals(0, result.getTotalElements()); - assertEquals(0, result.getContent().size()); - verifyNoInteractions(repo); + verify(repo) + .findByTenantIdAndAccountIdAndPlayableStateKey(2L, 1L, "instance:91", Pageable.unpaged()); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java index ed18f394c3..f6b8c8bbff 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java @@ -4,11 +4,9 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.Optional; -import java.util.UUID; import net.firedevops.firemud.entitymanagement.dto.CharacterDto; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; @@ -18,6 +16,7 @@ import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import org.mockito.Mockito; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; class CharacterServiceImplTest { @@ -25,6 +24,17 @@ class CharacterServiceImplTest { void gainExperienceLevelsUp() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); + var cacheManager = new ConcurrentMapCacheManager("characterGraph"); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + CharacterServiceImpl service = + new CharacterServiceImpl( + repo, + mapper, + cacheManager, + meterRegistry, + new PlayableStateKeyResolver(), + new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); Character character = new Character(); character.setId(1L); @@ -40,15 +50,9 @@ void gainExperienceLevelsUp() { character.setStamina(1); character.setHealth(10); character.setMana(5); - character.setActorIdentity( - ownerResolvedIdentity(1L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); - ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); - when(resolver.requireScopedCharacter( - 1L, 1L, "live", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(character); - CharacterServiceImpl service = - new CharacterServiceImpl(repo, mapper, new PlayableStateKeyResolver(), resolver); + when(repo.findByIdAndTenantIdAndPlayableStateKey(1L, 1L, "shared-live")) + .thenReturn(Optional.of(character)); when(repo.save(any(Character.class))).thenAnswer(a -> a.getArgument(0)); CharacterDto dto = @@ -63,12 +67,17 @@ void gainExperienceLevelsUp() { void getWithInventoryReturnsDto() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); CharacterMapper mapper = Mappers.getMapper(CharacterMapper.class); + var cacheManager = new ConcurrentMapCacheManager("characterGraph"); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); CharacterServiceImpl service = new CharacterServiceImpl( repo, mapper, + cacheManager, + meterRegistry, new PlayableStateKeyResolver(), new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); Character character = new Character(); character.setId(1L); @@ -76,25 +85,11 @@ void getWithInventoryReturnsDto() { character.setAccountId(1L); character.setPlayableStateKey("shared-live"); character.setName("Test"); - character.setActorIdentity( - ownerResolvedIdentity(1L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(repo.findWithInventoryById(1L)).thenReturn(Optional.of(character)); CharacterDto dto = service.getWithInventory(1L); assertEquals(1L, dto.id()); assertEquals(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, dto.playableStateScope()); - Mockito.verify(repo).findWithInventoryById(1L); - } - - private static ActorIdentity ownerResolvedIdentity(Long id, PlayableStateScope scope) { - return new ActorIdentity( - UUID.nameUUIDFromBytes(("character-" + id).getBytes()), - UUID.fromString("20000000-0000-4000-8000-000000000002"), - UUID.fromString("10000000-0000-4000-8000-000000000001"), - UUID.fromString("30000000-0000-4000-8000-000000000003"), - scope, - ActorIdentityStatus.OWNER_RESOLVED, - null); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java index 0d8cc614bf..b391495ef6 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java @@ -20,8 +20,6 @@ import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; -import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; -import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -44,7 +42,7 @@ void listContainerContentsReturnsInstanceBackedDtos() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -96,7 +94,7 @@ void listContainerContentsReturnsStackBackedDtos() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -155,7 +153,7 @@ void putItemIntoContainerMovesSelectedInstancesIntoContainer() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -214,7 +212,7 @@ void putItemIntoContainerMovesStackQuantity() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -293,7 +291,7 @@ void takeItemFromContainerUsesExplicitItemInstanceId() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -351,7 +349,7 @@ void putItemIntoContainerRejectsNestedContainerViaSharedHolderPolicy() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -396,7 +394,7 @@ void putItemIntoContainerSelectsExplicitStackFamilyWhenMultipleFamiliesExist() { new ContainerServiceImpl( containerInstanceRepo, itemInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, new ItemTransferSupport(), @@ -471,37 +469,6 @@ private static Character character(Long id, Long tenantId) { return character; } - // These business-logic tests isolate item behavior after the scope guard. The mock only - // accepts a matching legacy playable-state key and is not owner-provenance proof. - private static ScopedCharacterResolver mockedScopedCharacterResolver( - CharacterRepository characterRepo) { - ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); - Mockito.when( - resolver.requireScopedCharacter( - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.nullable(String.class), - Mockito.any(PlayableStateScope.class))) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long characterId = invocation.getArgument(1); - String gameInstanceId = invocation.getArgument(2); - PlayableStateScope scope = invocation.getArgument(3); - String playableStateKey = - new PlayableStateKeyResolver().resolve(gameInstanceId, scope); - Character character = - characterRepo - .findByIdAndTenantId(characterId, tenantId) - .orElseThrow(() -> new IllegalArgumentException("Character not found")); - if (!playableStateKey.equals(character.getPlayableStateKey())) { - throw new IllegalArgumentException("Test fixture playable-state scope mismatch"); - } - return character; - }); - return resolver; - } - private static Item item( Long id, Long tenantId, String name, boolean container, boolean stackable) { Item item = new Item(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java index f3f564c766..2715e33747 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java @@ -22,8 +22,6 @@ import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.service.EquipmentSlotIncompatibleException; -import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; -import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -49,7 +47,7 @@ void listEquipmentReturnsInstanceBackedDtos() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -97,7 +95,7 @@ void wearItemMovesCarriedInstanceIntoSlot() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), itemTransferAuditWriter, @@ -158,7 +156,7 @@ void wearItemRejectsStaleSourceMismatch() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), itemTransferAuditWriter, @@ -205,7 +203,7 @@ void removeWornItemReturnsRemovedSlotWhileMovingItemIntoInventory() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), itemTransferAuditWriter, @@ -261,7 +259,7 @@ void removeWornItemRejectsStaleEquippedSourceMismatch() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -300,7 +298,7 @@ void wearItemRequiresAuthoredSlotWhenEquipmentSchemaExists() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -341,7 +339,7 @@ void wearItemRequiresBodyLayoutToSupportAuthoredSlot() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -389,7 +387,7 @@ void wearItemRequiresItemSlotGroupToMatchAuthoredSlotGroup() { new EquipmentServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(charRepo), + charRepo, itemRepo, new ItemTransferSupport(), Mockito.mock(ItemTransferAuditWriter.class), @@ -423,37 +421,6 @@ private static Character character(Long id, Long tenantId) { return character; } - // These business-logic tests isolate equipment behavior after the scope guard. The mock only - // accepts a matching legacy playable-state key and is not owner-provenance proof. - private static ScopedCharacterResolver mockedScopedCharacterResolver( - CharacterRepository characterRepo) { - ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); - Mockito.when( - resolver.requireScopedCharacter( - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.nullable(String.class), - Mockito.any(PlayableStateScope.class))) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long characterId = invocation.getArgument(1); - String gameInstanceId = invocation.getArgument(2); - PlayableStateScope scope = invocation.getArgument(3); - String playableStateKey = - new PlayableStateKeyResolver().resolve(gameInstanceId, scope); - Character character = - characterRepo - .findByIdAndTenantId(characterId, tenantId) - .orElseThrow(() -> new IllegalArgumentException("Character not found")); - if (!playableStateKey.equals(character.getPlayableStateKey())) { - throw new IllegalArgumentException("Test fixture playable-state scope mismatch"); - } - return character; - }); - return resolver; - } - private static Item item( Long id, Long tenantId, String name, boolean container, String equipmentSlot) { Item item = new Item(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java index 9cb9627b3f..4ca96c334a 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java @@ -31,28 +31,11 @@ void setUp() { characterRepository = Mockito.mock(net.firedevops.firemud.entitymanagement.repository.CharacterRepository.class); CharacterFriendMapper mapper = Mappers.getMapper(CharacterFriendMapper.class); - ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); - // These friend tests isolate relationship behavior after the playable-state scope guard; - // the fixture does not establish canonical owner provenance. - Mockito.when( - resolver.requireScopedCharacter( - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.anyString(), - Mockito.any(PlayableStateScope.class))) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long characterId = invocation.getArgument(1); - String gameInstanceId = invocation.getArgument(2); - PlayableStateScope scope = invocation.getArgument(3); - String playableStateKey = - new PlayableStateKeyResolver().resolve(gameInstanceId, scope); - return characterRepository - .findByIdAndTenantIdAndPlayableStateKey(characterId, tenantId, playableStateKey) - .orElseThrow(() -> new IllegalArgumentException("Character not found")); - }); - service = new FriendServiceImpl(repository, mapper, resolver); + service = + new FriendServiceImpl( + repository, + mapper, + new ScopedCharacterResolver(characterRepository, new PlayableStateKeyResolver())); } @Test diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java index 8abd296044..5001e150c3 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java @@ -23,8 +23,6 @@ import net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.ItemStackRepository; -import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; -import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -887,7 +885,7 @@ private InventoryServiceImpl service( return new InventoryServiceImpl( itemInstanceRepo, containerInstanceRepo, - mockedScopedCharacterResolver(characterRepo), + characterRepo, itemRepo, itemStackRepo, visibleRefAllocator, @@ -897,37 +895,6 @@ private InventoryServiceImpl service( new StackableItemSupport()); } - // This collaborator mock keeps these inventory tests focused on item behavior after the - // playable-state scope guard. It does not provide owner-provenance or runtime identity proof. - private static ScopedCharacterResolver mockedScopedCharacterResolver( - CharacterRepository characterRepo) { - ScopedCharacterResolver resolver = Mockito.mock(ScopedCharacterResolver.class); - Mockito.when( - resolver.requireScopedCharacter( - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.nullable(String.class), - Mockito.any(PlayableStateScope.class))) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long characterId = invocation.getArgument(1); - String gameInstanceId = invocation.getArgument(2); - PlayableStateScope scope = invocation.getArgument(3); - String playableStateKey = - new PlayableStateKeyResolver().resolve(gameInstanceId, scope); - Character character = - characterRepo - .findByIdAndTenantId(characterId, tenantId) - .orElseThrow(() -> new IllegalArgumentException("Character not found")); - if (!playableStateKey.equals(character.getPlayableStateKey())) { - throw new IllegalArgumentException("Test fixture playable-state scope mismatch"); - } - return character; - }); - return resolver; - } - private static Character character(Long id, Long tenantId) { Character character = new Character(); character.setId(id); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java deleted file mode 100644 index 6f1cba49c5..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.firedevops.firemud.entitymanagement.service.impl; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.when; - -import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -class RuntimeInstanceCleanupServiceImplTest { - private static final Long TENANT_ID = 29L; - private static final String GAME_INSTANCE_ID = "runtime-opaque"; - private static final String TERMINATION_REQUEST_ID = "termination-request"; - - @Test - void observedEmptyTargetReturnsZeroCountsWithoutDeletingAnyFamily() { - Dependencies dependencies = new Dependencies(); - when(dependencies.retentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - TENANT_ID, GAME_INSTANCE_ID)) - .thenReturn(false); - - var result = - dependencies - .service() - .cleanupRuntimeInstance(TENANT_ID, GAME_INSTANCE_ID, TERMINATION_REQUEST_ID); - - assertThat(result.deletedRoomGroundEntries()).isZero(); - assertThat(result.deletedItemStacks()).isZero(); - assertThat(result.deletedItemInstances()).isZero(); - assertThat(result.deletedContainerInstances()).isZero(); - } - - @Test - void unclassifiedOrQuarantinedEvidenceDeniesCleanupWithoutMutation() { - Dependencies dependencies = new Dependencies(); - when(dependencies.retentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - TENANT_ID, GAME_INSTANCE_ID)) - .thenReturn(true); - - assertThatThrownBy( - () -> - dependencies - .service() - .cleanupRuntimeInstance(TENANT_ID, GAME_INSTANCE_ID, TERMINATION_REQUEST_ID)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); - } - - private static final class Dependencies { - private final QuarantinedActorRetentionRepository retentionRepository = - Mockito.mock(QuarantinedActorRetentionRepository.class); - - private RuntimeInstanceCleanupServiceImpl service() { - return new RuntimeInstanceCleanupServiceImpl(retentionRepository); - } - } -} diff --git a/services/entity-management-service/src/test/resources/application.yml b/services/entity-management-service/src/test/resources/application.yml index cd57d6839c..ec1671a55b 100644 --- a/services/entity-management-service/src/test/resources/application.yml +++ b/services/entity-management-service/src/test/resources/application.yml @@ -1,7 +1,3 @@ FIREMUD_GRPC_CERT_CHAIN_PATH: classpath:certs/dev-cert.pem FIREMUD_GRPC_PRIVATE_KEY_PATH: classpath:certs/dev-key.pem FIREMUD_GRPC_CA_CERT_PATH: classpath:certs/dev-ca.pem -spring: - flyway: - postgresql: - transactional-lock: false From 7760c0f6ec8eb5a13606d1f22b55acfcd573896f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:37:34 +1300 Subject: [PATCH 16/39] Record staged owner-source proof and wrong-checkout safety incident --- .../microservices/account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 7159ccc74e..5460e97b28 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -10,7 +10,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation. New repository-created Accounts and a genuinely new issuer receive these baselines; retained rows are not backfilled. Exact security-relevant Account updates compose source generation, issuance fence, canonical event, and current readback in their owner transaction. The owner-local first-JOIN producer/coordinator retains membership, pair/event, audit, and terminal-operation evidence. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime wiring. Reconciled V40/source-currentness/coordinator proof remains pending; see the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. -Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. Focused unit/controller and PostgreSQL integration proof sources are included; validation and live PostgreSQL execution are deferred, so the RPC is not runtime-ready or admission authority. +Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index cebc28b28f..1c57daf723 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -67,3 +67,9 @@ Entry format: - Context: The PR #3078 watcher initially counted the first 30 jobs as the full run; complete coverage showed 40 jobs, with 38 successful and two skipped. Required gates were green and the merge remained valid. - Observation: The run header also transiently reported queued while jobs progressed, then completed successfully; its cause remains unknown. Partial job pages and a transient header cannot establish a full-run count or terminal outcome. - Expected pattern: Fetch complete pagination, reconcile `total_count`, and verify unique job IDs before reporting full-run counts. Report required-job/gate proof separately from the terminal run header, without inferring the cause of inconsistent intermediate snapshots. + +- `2026-10-09`: A shell workdir does not redirect patch-tool targets + - Context: Gameplay's Account integration helper used relative patch headers despite its absolute-target instruction. The patch tool wrote 53 additions into the shared inspection checkout instead of the assigned worktree; 16 paths were inside directories already reported as untracked, without retained before-images. + - Expected pattern: Verify the absolute worktree, branch, head, and relevant status before editing; use absolute paths in every patch header and verify the first write in the assigned checkout. A shell command's working directory does not establish a separate patch tool's destination. Preserve before-images when an assigned path already contains uncommitted work. + - Current status: The helper corrected all owned targets. Only 37 confirmed new wrong-checkout paths were removed after verifying identical receiver and owned-target copies; the 16 uncertain paths remain untouched for independent recovery assessment. Matching the newly written bytes does not prove prior contents survived. Exact paths and evidence are retained in the controller inbox and active job, not another ledger. + - Reconsideration trigger: Close the uncertain recovery only after a trusted before-image or the owning human establishes the previous content; do not infer preservation from hashes of replacement copies. From 82a7e6980c8fca85f5d08329a6f187d00e5cb10e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:15:15 +1300 Subject: [PATCH 17/39] Verify current tenant source for JOIN and repair Account proof fixtures --- design/project-management/ai-observations.md | 1 + .../player-access-and-session.md | 2 + ...countMembershipAuthorityEventProducer.java | 92 +++++- ...untActorStagingEligibilityGrpcService.java | 7 + ...account_tenant_authority_source_bridge.sql | 2 +- ...EntitlementPersistenceIntegrationTest.java | 25 +- ...stJoinAuthorityStorageIntegrationTest.java | 4 +- ...ingEligibilityPostgresIntegrationTest.java | 6 +- ...anonicalFirstJoinEventIntegrationTest.java | 90 +++++- ...thorityEventProducerCanonicalJoinTest.java | 261 +++++++++++++++++- ...ctorStagingEligibilityGrpcServiceTest.java | 20 ++ ...orldCanonicalInitialAdmissionHoldTest.java | 2 +- 12 files changed, 483 insertions(+), 29 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1c57daf723..75133bf080 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -70,6 +70,7 @@ Entry format: - `2026-10-09`: A shell workdir does not redirect patch-tool targets - Context: Gameplay's Account integration helper used relative patch headers despite its absolute-target instruction. The patch tool wrote 53 additions into the shared inspection checkout instead of the assigned worktree; 16 paths were inside directories already reported as untracked, without retained before-images. + - Observation: For those 16 paths, the prior contents and whether they were overwritten remain unknown because no before-images were retained; matching replacement copies do not establish preservation. - Expected pattern: Verify the absolute worktree, branch, head, and relevant status before editing; use absolute paths in every patch header and verify the first write in the assigned checkout. A shell command's working directory does not establish a separate patch tool's destination. Preserve before-images when an assigned path already contains uncommitted work. - Current status: The helper corrected all owned targets. Only 37 confirmed new wrong-checkout paths were removed after verifying identical receiver and owned-target copies; the 16 uncertain paths remain untouched for independent recovery assessment. Matching the newly written bytes does not prove prior contents survived. Exact paths and evidence are retained in the controller inbox and active job, not another ledger. - Reconsideration trigger: Close the uncertain recovery only after a trusted before-image or the owning human establishes the previous content; do not infer preservation from hashes of replacement copies. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8faf668d98..a3e8951a44 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +Canonical first-JOIN membership-event production preserves the exact fresh tenant 1/1 baseline and permits later tenant authority only after Account's current typed tenant event, fresh Game Design provenance, and both composite generation/source-version values match. The event carries the linked tenant billing cutoff from those source coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Consolidated validation passed 593 Account unit cases, five shared World hold cases, jOOQ generation, and integration-test compilation. The new physical PostgreSQL case is compiled but unrun locally; the earlier hosted Account run executed 74 integration cases with four fixture failures, whose corrections still require exact-head hosted proof. + Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. Account's persisted UUID now backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. Authentication results and JWTs, profile and tenant DTO identity fields, Game Session carriers, `PLAY`, and Entity Management remain outside this output slice. Numeric Account-claim consumers remain outside this slice in common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no UUID-authentication or downstream runtime-proof upgrade. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index b5bd710108..529bceb663 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -32,6 +33,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; @@ -59,6 +61,7 @@ public class AccountMembershipAuthorityEventProducer { private final AccountAuthorityGenerationRepository authorityGenerationRepository; private final AccountAuthorityOutboxRepository authorityOutboxRepository; private final AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEventRepository; @SuppressFBWarnings( value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, @@ -73,7 +76,8 @@ public AccountMembershipAuthorityEventProducer( AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, - AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository) { + AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEventRepository) { this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository); this.accountRepository = Objects.requireNonNull(accountRepository); this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); @@ -82,6 +86,7 @@ public AccountMembershipAuthorityEventProducer( this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository); this.sourceEvidenceRepository = Objects.requireNonNull(sourceEvidenceRepository); + this.tenantAuthorityEventRepository = Objects.requireNonNull(tenantAuthorityEventRepository); } /** @@ -168,17 +173,34 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( CompositeSnapshot authority = authorityGenerationRepository.readCompositeSnapshot( ACCOUNT_JWT_ISSUER, accountUuid, List.of(tenantUuid), List.of(tenantUuid)); + ScopeState tenant = only(authority.tenants(), "tenant"); IssuerAccountSourceSnapshot sourceSnapshot = sourceEvidenceRepository.readCurrentIssuerAccountSources(ACCOUNT_JWT_ISSUER, accountUuid); + TenantAuthorityEventV1Codec.Event tenantSourceEvent = + readCurrentTenantSourceEvent(tenantUuid, provenance, tenant); requireCurrentAuthority( - authority, sourceSnapshot, account.getId(), accountUuid, tenantUuid, membership); + authority, + sourceSnapshot, + account.getId(), + accountUuid, + tenantUuid, + membership, + provenance, + tenantSourceEvent); if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { throw new IllegalStateException( "Canonical first JOIN cannot publish over retained membership-event history"); } Checkpoint checkpoint = appendFirstJoinEvent( - streamKey, requestId, scope, membership, exactRoles, authority, sourceSnapshot); + streamKey, + requestId, + scope, + membership, + exactRoles, + authority, + sourceSnapshot, + tenantSourceEvent); PairAuthority committed = pairAuthorityRepository.commitTransition( pair, @@ -209,7 +231,8 @@ private Checkpoint appendFirstJoinEvent( AccountTenantMembership membership, List roles, CompositeSnapshot authority, - IssuerAccountSourceSnapshot sourceSnapshot) { + IssuerAccountSourceSnapshot sourceSnapshot, + TenantAuthorityEventV1Codec.Event tenantSourceEvent) { String eventId = eventIdForRequest(requestId); MembershipEvent[] candidate = new MembershipEvent[1]; Event appended = @@ -229,6 +252,7 @@ private Checkpoint appendFirstJoinEvent( roles, authority, sourceSnapshot, + tenantSourceEvent, eventId, requestId, sequence)); @@ -324,6 +348,7 @@ private static Map membershipEventPreimage( List roles, CompositeSnapshot authority, IssuerAccountSourceSnapshot sourceSnapshot, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, String eventId, String requestId, long sequence) { @@ -352,6 +377,21 @@ private static Map membershipEventPreimage( "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), "outboxStreamKey", cutoff.outboxStreamKey(), "outboxSequence", cutoff.outboxSequence()))); + if (tenantSourceEvent != null) { + authorityTuple.put( + "tenantBillingCutoff", + Map.of( + tenantUuid.toString(), + Map.of( + "tenantAuthorityGeneration", + decimal(tenantSourceEvent.tenantAuthorityGeneration()), + "tenantBillingSequence", + decimal(tenantSourceEvent.tenantBillingSequence()), + "outboxStreamKey", + tenantSourceEvent.outboxStreamKey(), + "outboxSequence", + decimal(tenantSourceEvent.outboxSequence())))); + } Map event = new LinkedHashMap<>(); event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); @@ -521,17 +561,15 @@ private void requireCurrentAuthority( long accountRowId, UUID accountUuid, UUID tenantUuid, - AccountTenantMembership membership) { + AccountTenantMembership membership, + VerifiedTenantProvenance provenance, + TenantAuthorityEventV1Codec.Event tenantSourceEvent) { ScopeState member = only(snapshot.memberships(), "membership"); ScopeState tenant = only(snapshot.tenants(), "tenant"); if (!AuthorityScope.issuer(ACCOUNT_JWT_ISSUER).equals(snapshot.issuer().scope()) || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) - // Account currently has no tenant source-event readback for later tenant mutations. The - // exact fresh tenant association proves the original identity only, so do not accept a - // changed tenant authority generation until its owner source can prove that transition. - || tenant.generation() != 1L - || tenant.sourceVersion() != 1L + || !tenantSourceEvidenceMatches(tenantSourceEvent, tenant, tenantUuid, provenance) || !AuthorityScope.membership(accountUuid, tenantUuid).equals(member.scope()) || member.generation() != membership.getMembershipAuthorityGeneration() || !accountUuid.equals(snapshot.issuanceFence().accountId()) @@ -563,6 +601,40 @@ private void requireCurrentAuthority( } } + private TenantAuthorityEventV1Codec.Event readCurrentTenantSourceEvent( + UUID tenantUuid, VerifiedTenantProvenance provenance, ScopeState tenantAuthority) { + if (tenantAuthority.generation() == 1L && tenantAuthority.sourceVersion() == 1L) { + return null; + } + TenantAuthorityEventV1Codec.Event event = + tenantAuthorityEventRepository.readCurrentByTenant(tenantUuid); + if (!tenantSourceEvidenceMatches(event, tenantAuthority, tenantUuid, provenance)) { + throw new IllegalStateException( + "Canonical first JOIN requires exact current Account, source, and tenant authority evidence"); + } + return event; + } + + private static boolean tenantSourceEvidenceMatches( + TenantAuthorityEventV1Codec.Event event, + ScopeState tenantAuthority, + UUID tenantUuid, + VerifiedTenantProvenance provenance) { + if (event == null) { + return tenantAuthority.generation() == 1L && tenantAuthority.sourceVersion() == 1L; + } + var source = event.sourceEvidence(); + return event.tenantId().equals(tenantUuid) + && event.tenantAuthorityGeneration() == tenantAuthority.generation() + && event.tenantAuthoritySourceVersion() == tenantAuthority.sourceVersion() + && "NEW_GAME_ROW".equals(source.provenanceKind()) + && tenantUuid.equals(source.canonicalTenantId()) + && provenance.kind() == TenantProvenanceKind.FRESH_GAME_DESIGN + && provenance.legacyTenantId() == null + && provenance.sourceOperationId().equals(source.operationId()) + && provenance.digest().equals(source.evidenceDigest()); + } + private static PairAuthority requirePositiveFirstJoinPair( PairAuthority pair, AccountTenantMembership membership) { if (!pair.membershipExists() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java index f335565c55..61f1f02b8e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java @@ -26,6 +26,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.CannotCreateTransactionException; /** Same-namespace Entity-only mTLS transport for Account staging evidence, disabled by default. */ @GrpcService @@ -93,6 +94,12 @@ public void resolvePreseededActorStagingEligibility( accountUuid, tenantUuid, purpose); + } catch (CannotCreateTransactionException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Account owner evidence is temporarily unavailable"); + return; } catch (DataAccessResourceFailureException unavailable) { fail( responseObserver, diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql index 1b641d4d2e..2bb9424e7c 100644 --- a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -479,4 +479,4 @@ CREATE TRIGGER account_demo_entitlement_authority_event CREATE TRIGGER account_demo_entitlement_authority_receipt BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlement_operations FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_receipt_guard(); --- [jooq ignore end] +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index d43be29971..2ab572c80b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -350,13 +350,24 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc .hasMessageContaining("Demo entitlement identity is immutable and version advances by one"); assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) .isEqualTo(updated); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> tenantAuthorityEvents.readCurrentByTenant(tenantId))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("differs from its exact committed billing event"); + var currentAuthority = + inTransaction( + context.transaction(), () -> tenantAuthorityEvents.readCurrentByTenant(tenantId)); + assertThat(currentAuthority.requestId()).isEqualTo(update.requestId()); + assertThat(currentAuthority.requestDigest()).isEqualTo(update.requestDigest()); + assertThat(currentAuthority.tenantId()).isEqualTo(tenantId); + assertThat(currentAuthority.tenantAuthorityGeneration()) + .isEqualTo(updated.tenantAuthorityGeneration()); + assertThat(currentAuthority.tenantAuthoritySourceVersion()) + .isEqualTo(updated.tenantAuthoritySourceVersion()); + assertThat(currentAuthority.outboxSequence()) + .isEqualTo(updated.tenantAuthorityOutboxSequence()); + assertThat(currentAuthority.eventId()).isEqualTo(updated.tenantAuthorityEventId()); + assertThat(currentAuthority.eventDigest()).isEqualTo(updated.tenantAuthorityEventDigest()); + assertThat(currentAuthority.tenantBillingSequence()).isEqualTo(updated.tenantBillingSequence()); + assertThat(currentAuthority.tenantBillingEventId()).isEqualTo(updated.eventId()); + assertThat(currentAuthority.tenantBillingEventDigest()).isEqualTo(updated.eventDigest()); + assertThat(currentAuthority.sourceEvidence()).isEqualTo(source); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index 29c8966353..f81e90f9e7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -76,7 +76,7 @@ void dropRunOwnedSchemas() { @Test void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { - TestContext context = newTestContext(); + TestContext context = newTestContextAtV39(); AccountAuthorityOutboxRepository repository = context.repository(); TransactionTemplate transaction = context.transaction(); String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); @@ -333,7 +333,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo @Test void missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent() { - TestContext context = newTestContext(); + TestContext context = newTestContextAtV39(); AccountAuthorityOutboxRepository repository = context.repository(); TransactionTemplate transaction = context.transaction(); DSLContext dsl = context.dsl(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java index f5c95ce65e..0ee66e66ff 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java @@ -267,7 +267,8 @@ dsl, new LegacyTenantSourceEvidence(dsl), TEST_NAMESPACE), roles, generations, outbox, - sourceEvidence); + sourceEvidence, + tenantEvents); seedMembershipOperation(); } @@ -419,7 +420,8 @@ private String membershipStream() { private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); - String sourceTenantKey = "actor-staging-" + UUID.randomUUID().toString().replace("-", ""); + String sourceTenantKey = + "actor-stage-" + UUID.randomUUID().toString().replace("-", "").substring(0, 24); String requestDigest = GameTenantCreationDigest.requestDigest( TEST_NAMESPACE, requestId, sourceTenantKey, "Actor staging eligibility test", null); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index cc42d0a4fb..347a202234 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -11,12 +11,15 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; @@ -24,6 +27,8 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; @@ -136,6 +141,44 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { .isEqualTo(1L); } + @Test + void laterTenantAuthorityUsesTheCurrentAccountSourceEventAndItsExactBillingCutoff() { + Fixture fixture = newFixture(); + DemoTenantEntitlementSnapshot entitlement = fixture.provisionCurrentTenantEntitlement(); + + var proof = fixture.commitFirstJoin(); + String stream = fixture.membershipStream(); + AccountAuthorityOutboxRepository.Event membershipEvent = + fixture.inTransaction( + () -> fixture.outbox.findEvent(stream, proof.eventSequence()).orElseThrow()); + var decoded = + MembershipAuthorityEventV1Codec.verify( + new String(membershipEvent.payload(), StandardCharsets.UTF_8)); + var currentTenantEvent = + fixture.inTransaction( + () -> fixture.tenantAuthorityEvents.readCurrentByTenant(fixture.tenantUuid)); + + assertThat(entitlement.tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(entitlement.tenantAuthoritySourceVersion()).isEqualTo(3L); + assertThat(entitlement.tenantBillingSequence()).isEqualTo(2L); + assertThat(entitlement.tenantAuthorityOutboxSequence()).isEqualTo(2L); + assertThat(decoded.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid.toString(), "3")); + assertThat(decoded.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + fixture.tenantUuid.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "3", "2", currentTenantEvent.outboxStreamKey(), "2"))); + assertThat(currentTenantEvent.tenantBillingEventId()).isEqualTo(entitlement.eventId()); + assertThat(currentTenantEvent.tenantBillingEventDigest()).isEqualTo(entitlement.eventDigest()); + assertThat(decoded.eventId()).isEqualTo(proof.eventId()); + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isEqualTo(1L); + assertThat(fixture.count("account_authority_outbox_events", "outbox_stream_key", stream)) + .isEqualTo(1L); + } + @Test void pairCasFailureRollsBackMembershipAndTheActualOutboxAppend() { Fixture fixture = newFixture(); @@ -287,6 +330,8 @@ private static final class Fixture { private final AccountAuthorityGenerationRepository generations; private final AccountAuthorityOutboxRepository outbox; private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + private final AccountDemoTenantEntitlementRepository demoEntitlements; private final AccountAuditOutboxRepository auditOutbox; private final AccountJoinOperationRepository operations; private final AccountMembershipAuthorityEventProducer producer; @@ -312,6 +357,13 @@ private Fixture(TestContext context) { this.generations = new AccountAuthorityGenerationRepository(dsl); this.outbox = new AccountAuthorityOutboxRepository(dsl); this.sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billingOutbox = new AccountTenantEntitlementOutboxRepository(dsl); + this.tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + this.demoEntitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantAuthorityEvents); this.auditOutbox = new AccountAuditOutboxRepository(dsl); var legacyAssociationRepository = org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class); @@ -322,7 +374,15 @@ private Fixture(TestContext context) { this.operations = new AccountJoinOperationRepository(dsl, connectScopes); this.producer = new AccountMembershipAuthorityEventProducer( - operations, accounts, pairs, memberships, roles, generations, outbox, sourceEvidence); + operations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sourceEvidence, + tenantAuthorityEvents); this.terminalCoordinator = new AccountCanonicalFirstJoinTerminalCoordinator( accounts, operations, memberships, roles, outbox, pairs, auditOutbox, producer); @@ -364,6 +424,34 @@ private void seedOwnerRowsAndOperation() { }); } + private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { + return inTransaction( + () -> { + DemoTenantEntitlementSnapshot created = + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), null), tenantEvidence); + return demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), created), tenantEvidence); + }); + } + + private DemoTenantEntitlementRequest entitlementRequest( + UUID requestId, DemoTenantEntitlementSnapshot current) { + return new DemoTenantEntitlementRequest( + requestId, + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + current == null ? null : current.entitlementVersion(), + current == null ? null : current.tenantAuthorityGeneration(), + current == null ? null : current.tenantAuthoritySourceVersion(), + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } + private AccountAuthorityOutboxRepository.Checkpoint writeAndPublish() { return inTransaction( () -> { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index a35b9842cf..38b7c36b92 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -24,6 +24,9 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -50,6 +53,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; @@ -57,6 +61,8 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -70,6 +76,9 @@ class AccountMembershipAuthorityEventProducerCanonicalJoinTest { private static final UUID INSTANCE_UUID = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID TENANT_OPERATION_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String TENANT_SOURCE_NAMESPACE = "account-service"; + private static final FreshTenantCreationEvidence CURRENT_TENANT_SOURCE = + freshTenantEvidence(TENANT_UUID, TENANT_OPERATION_ID); private static final String REQUEST_ID = "global-request-1"; private static final String CALLER_BINDING = "server-verified-caller"; private static final String MEMBERSHIP_STREAM = @@ -145,6 +154,7 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); assertThat(event.authorityTuple().accountSecurityCutoff()).isEmpty(); assertThat(event.authorityTuple().tenantBillingCutoff()).isEmpty(); + verifyNoInteractions(fixture.tenantAuthorityEvents); var order = inOrder(fixture.accounts, fixture.joinOperations, fixture.memberships); order.verify(fixture.accounts).findByAccountUuid(ACCOUNT_UUID); @@ -274,6 +284,71 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { .readCheckpoint("account:auth-authority:v1:tenant/" + TENANT_UUID); } + @Test + void firstJoinAcceptsLaterTenantAuthorityOnlyWithExactCurrentTenantSourceAndBillingCutoff() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 2L, 1L)); + TenantAuthorityEventV1Codec.Event tenantSourceEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 9L, 7L); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)) + .thenReturn(tenantSourceEvent); + fixture.startWritableTransaction(); + + AtomicReference committedEvent = new AtomicReference<>(); + AtomicInteger membershipCheckpointReads = new AtomicInteger(); + when(fixture.outbox.readCheckpoint(any(String.class))) + .thenAnswer( + invocation -> + membershipCheckpointReads.getAndIncrement() == 0 + ? Optional.empty() + : Optional.of(fixture.checkpoint(committedEvent.get()))); + when(fixture.outbox.append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class))) + .thenAnswer( + invocation -> { + LongFunction factory = invocation.getArgument(2); + EventEvidence evidence = factory.apply(1L); + Event event = + new Event( + MEMBERSHIP_STREAM, + REQUEST_ID, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + committedEvent.set(event); + return event; + }); + when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)) + .thenAnswer(invocation -> Optional.of(committedEvent.get())); + when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)) + .thenAnswer(invocation -> Optional.of(committedEvent.get())); + when(fixture.pairs.commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class))) + .thenAnswer( + invocation -> { + PairTransition transition = invocation.getArgument(1); + return fixture.positivePair(transition.eventId(), transition.eventDigest()); + }); + + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING); + + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(committedEvent.get().payload(), StandardCharsets.UTF_8)); + assertThat(event.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(TENANT_UUID.toString(), "2")); + assertThat(event.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + TENANT_UUID.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "2", "7", "account:auth-authority:v1:tenant/" + TENANT_UUID, "9"))); + verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); + } + @Test void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { Fixture fixture = new Fixture(); @@ -293,6 +368,61 @@ void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current Account, source, and tenant authority evidence"); + verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesCurrentTenantSourceForAnotherTenantWithoutMutation() { + denyLaterTenantSource( + tenantAuthorityEvent( + UUID.fromString("99999999-9999-4999-8999-999999999999"), + TENANT_OPERATION_ID, + 2L, + 2L, + 9L, + 7L)); + } + + @Test + void firstJoinDeniesCurrentTenantSourceWithDifferentFreshGameDesignProvenance() { + denyLaterTenantSource( + tenantAuthorityEvent( + TENANT_UUID, UUID.fromString("77777777-7777-4777-8777-777777777777"), 2L, 2L, 9L, 7L)); + } + + @Test + void firstJoinDeniesTenantSourceGenerationThatDiffersFromCompositeSnapshot() { + denyLaterTenantSource(tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 3L, 2L, 9L, 7L)); + } + + @Test + void firstJoinDeniesTenantSourceVersionThatDiffersFromCompositeSnapshot() { + denyLaterTenantSource(tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 3L, 9L, 7L)); + } + + @Test + void firstJoinDeniesWhenTenantSourceRepositoryRejectsMissingOrMismatchedBillingEvidence() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 2L, 1L)); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)) + .thenThrow( + new IllegalStateException("Current tenant billing event is absent or mismatched")); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("billing event is absent or mismatched"); + verify(fixture.outbox, never()) .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); verify(fixture.pairs, never()).commitTransition(any(), any()); @@ -378,7 +508,115 @@ void eventPublicationRequiresWritableAccountTransactionBeforeAnyLookup() { fixture.pairs, fixture.authority, fixture.outbox, - fixture.sourceEvidence); + fixture.sourceEvidence, + fixture.tenantAuthorityEvents); + } + + private void denyLaterTenantSource(TenantAuthorityEventV1Codec.Event event) { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 2L, 1L)); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current Account, source, and tenant authority evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( + UUID tenantUuid, + UUID sourceOperationId, + long tenantGeneration, + long tenantSourceVersion, + long authorityOutboxSequence, + long billingSequence) { + FreshTenantCreationEvidence source = freshTenantEvidence(tenantUuid, sourceOperationId); + UUID entitlementRequestId = + UUID.nameUUIDFromBytes( + ("tenant-entitlement:" + + tenantUuid + + ":" + + tenantGeneration + + ":" + + tenantSourceVersion) + .getBytes(StandardCharsets.UTF_8)); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + entitlementRequestId, + tenantUuid, + source.creationRequestId(), + source.requestDigest(), + 1L, + 1L, + 1L, + true, + true, + false, + false, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + var billingEvent = + DemoTenantEntitlementEventV1Codec.seal( + request, source, 2L, tenantGeneration, tenantSourceVersion, billingSequence); + return TenantAuthorityEventV1Codec.seal( + request, + source, + tenantGeneration, + tenantSourceVersion, + authorityOutboxSequence, + billingEvent); + } + + private static FreshTenantCreationEvidence freshTenantEvidence( + UUID tenantUuid, UUID sourceOperationId) { + UUID creationRequestId = + UUID.nameUUIDFromBytes( + ("tenant-create:" + tenantUuid + ":" + sourceOperationId) + .getBytes(StandardCharsets.UTF_8)); + String sourceGameTenantKey = + "fresh-" + + tenantUuid.toString().substring(0, 8) + + "-" + + sourceOperationId.toString().substring(0, 8); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + TENANT_SOURCE_NAMESPACE, + creationRequestId, + sourceGameTenantKey, + "Canonical JOIN tenant source", + null); + long sourceGameRowId = 91L; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + TENANT_SOURCE_NAMESPACE, + creationRequestId, + sourceOperationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + return new FreshTenantCreationEvidence( + 1, + TENANT_SOURCE_NAMESPACE, + creationRequestId, + sourceOperationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); } private static final class Fixture { @@ -397,9 +635,19 @@ private static final class Fixture { mock(AccountAuthorityOutboxRepository.class); private final AccountAuthoritySourceEvidenceRepository sourceEvidence = mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents = + mock(AccountTenantAuthorityEventRepository.class); private final AccountMembershipAuthorityEventProducer producer = new AccountMembershipAuthorityEventProducer( - joinOperations, accounts, pairs, memberships, roles, authority, outbox, sourceEvidence); + joinOperations, + accounts, + pairs, + memberships, + roles, + authority, + outbox, + sourceEvidence, + tenantAuthorityEvents); private final CanonicalJoinScopeV2 scope = scopeValue(); private final VerifiedTenantProvenance provenance = provenanceValue(); private final Account account = accountValue(); @@ -691,7 +939,10 @@ private static CanonicalJoinScopeV2 scopeValue() { private static VerifiedTenantProvenance provenanceValue() { return new VerifiedTenantProvenance( - null, TenantProvenanceKind.FRESH_GAME_DESIGN, TENANT_OPERATION_ID, DIGEST); + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + CURRENT_TENANT_SOURCE.operationId(), + CURRENT_TENANT_SOURCE.evidenceDigest()); } private static Account accountValue() { @@ -710,8 +961,8 @@ private static AccountTenantMembership membershipValue(Account account) { membership.setTenantId(null); membership.setTenantUuid(TENANT_UUID); membership.setTenantProvenanceKind(TenantProvenanceKind.FRESH_GAME_DESIGN.name()); - membership.setTenantSourceOperationId(TENANT_OPERATION_ID); - membership.setTenantProvenanceDigest(DIGEST); + membership.setTenantSourceOperationId(CURRENT_TENANT_SOURCE.operationId()); + membership.setTenantProvenanceDigest(CURRENT_TENANT_SOURCE.evidenceDigest()); membership.setMembershipVersion(2L); membership.setMembershipAuthorityGeneration(1L); membership.setLifecycleState("ACTIVE"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java index 3ca207bfff..d31b5cf1aa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java @@ -26,6 +26,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.io.FileSystemResource; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.util.StreamUtils; class AccountActorStagingEligibilityGrpcServiceTest { @@ -168,6 +169,25 @@ void distinguishesMissingCurrentEvidenceFromTemporarySourceFailure() { assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); } + @Test + void classifiesTransactionCreationFailureAsSanitizedUnavailable() { + when(ownerService.resolve( + 1, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + .thenThrow(new CannotCreateTransactionException("private database endpoint")); + + TestObserver unavailable = call(request(), ENTITY_URI); + + assertThat(status(unavailable)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failure.getDescription()) + .isEqualTo("Account owner evidence is temporarily unavailable") + .doesNotContain("private database endpoint"); + } + private TestObserver call( ResolvePreseededActorStagingEligibilityRequest request, String peerUri) { TestObserver observer = new TestObserver(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java index 1ec288c5fa..05404080d2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java @@ -1,4 +1,4 @@ -package unit.net.firedevops.firemud.common.world; +package net.firedevops.firemud.common.world; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; From 9d28e9f4f70ae3a456e0d019698c321fe8ebfe72 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:26:57 +1300 Subject: [PATCH 18/39] Share publication policy proof fixtures and align Account capability anchors --- .../player-access-and-session.md | 6 +- ...shedRealmEntryPolicyReadGrpcCodecTest.java | 290 +----------------- ...lishedRealmEntryPolicySetEvidenceTest.java | 4 +- 3 files changed, 14 insertions(+), 286 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index a3e8951a44..82647106be 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. -Canonical first-JOIN membership-event production preserves the exact fresh tenant 1/1 baseline and permits later tenant authority only after Account's current typed tenant event, fresh Game Design provenance, and both composite generation/source-version values match. The event carries the linked tenant billing cutoff from those source coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Consolidated validation passed 593 Account unit cases, five shared World hold cases, jOOQ generation, and integration-test compilation. The new physical PostgreSQL case is compiled but unrun locally; the earlier hosted Account run executed 74 integration cases with four fixture failures, whose corrections still require exact-head hosted proof. +Canonical first-JOIN membership-event production preserves the exact fresh tenant 1/1 baseline and permits later tenant authority only after Account's current typed tenant event, fresh Game Design provenance, and both composite generation/source-version values match. The event carries the linked tenant billing cutoff from those source coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Consolidated validation passed 593 Account unit cases, five shared World hold cases, jOOQ generation, and integration-test compilation. Current PostgreSQL-backed integration sources, including the new later-generation JOIN case, compiled but were unrun locally. An earlier hosted Account run executed 74 integration cases and found four fixture failures; their corrections are present, but this current head still requires exact-head hosted proof. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. @@ -46,8 +46,8 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountMembershipAuthorityEventProducer` emits the canonical tenant authority event with billing cutoff from fresh source coordinates, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java index 0eebaa9333..f5930862a6 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java @@ -5,31 +5,11 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import java.util.UUID; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; -import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; -import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; -import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import org.junit.jupiter.api.Test; @@ -39,12 +19,11 @@ /** Closed wire and complete-set proof over isolated publication fixture vectors. */ class PublishedRealmEntryPolicyReadGrpcCodecTest { - private static final String DIGEST = "sha256:" + "a".repeat(64); private static final ObjectMapper JSON = new ObjectMapper(); @Test void listAndResolveRoundTripTheCompleteOrderedSealedSet() throws Exception { - Fixture fixture = fixture(true); + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(true); var listRequest = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); var resolveRequest = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); @@ -75,7 +54,7 @@ void listAndResolveRoundTripTheCompleteOrderedSealedSet() throws Exception { @Test void requestsRejectUnknownFieldsUnsupportedSchemaAndNoncanonicalIdentityOrSelectors() throws Exception { - Fixture fixture = fixture(false); + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(false); var validList = PublishedRealmEntryPolicyReadGrpcCodec.toRequest( listRequest(fixture, "99999999-9999-4999-8999-999999999999")); @@ -130,7 +109,7 @@ void requestsRejectUnknownFieldsUnsupportedSchemaAndNoncanonicalIdentityOrSelect @Test void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { - Fixture fixture = fixture(false); + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(false); var request = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); var response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, fixture.set()); @@ -230,7 +209,7 @@ void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { @Test void completeCarrierRejectsCountOrderAndDigestSubstitutionAtTheWireBoundary() throws Exception { - Fixture fixture = fixture(true); + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(true); var request = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); byte[] canonical = fixture.set().canonicalBytes(); ObjectNode root = (ObjectNode) JSON.readTree(canonical); @@ -267,7 +246,7 @@ private static void assertRejectedSet( } private static PublishedRealmEntryPolicyReadGrpcCodec.ListRequest listRequest( - Fixture fixture, String readId) { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture, String readId) { return new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( "test", UUID.fromString(readId), @@ -276,7 +255,7 @@ private static PublishedRealmEntryPolicyReadGrpcCodec.ListRequest listRequest( } private static PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest resolveRequest( - Fixture fixture, String readId, String realmSlug) { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture, String readId, String realmSlug) { return new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( "test", UUID.fromString(readId), @@ -286,259 +265,8 @@ private static PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest resolveRequ realmSlug); } - private static Fixture fixture(boolean includeSide) throws Exception { - var operation = operation(); - var target = operation.account().input().selection().target(); - var sourceBinding = operation.account().input().selection().selectedCommit(); - var terminal = - new GameDesignPublicationTerminalEvidence( - operation.canonicalBytes(), Outcome.PUBLISHED, release(operation), 6L); - List sources = new ArrayList<>(); - sources.add( - source( - "main", - true, - "33333333-3333-4333-8333-333333333333", - "44444444-4444-4444-8444-444444444444", - "55555555-5555-4555-8555-555555555555")); - if (includeSide) { - sources.add( - source( - "side", - false, - "88888888-8888-4888-8888-888888888888", - "66666666-6666-4666-8666-666666666666", - "77777777-7777-4777-8777-777777777777")); - } - byte[] capture = capture(operation, sourceBinding, sources); - List policies = - sources.stream() - .map( - source -> { - UUID policyId = UUID.fromString(source.policyId()); - return new PublishedRealmEntryPolicyEvidence( - policyId, - UUID.fromString(source.commitId()), - UUID.fromString(source.revisionId()), - "source-" + source.revisionId(), - source.policy(), - PublishedRealmEntryPolicySetEvidence.policyDigest( - policyId, - target, - terminal.releaseContent().versionNumber(), - terminal.publishedReleaseBundleRef(), - terminal.publishedReleaseBundleDigest(), - terminal.releaseContent().publishWorkflowId(), - terminal.releaseContent().manifestHash(), - UUID.fromString(source.commitId()), - UUID.fromString(source.revisionId()), - "source-" + source.revisionId(), - source.policy())); - }) - .toList(); - var release = terminal.releaseContent(); - String setDigest = - PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( - target, - release.versionNumber(), - sourceBinding.commitId(), - "43", - release.publishedReleaseBundleRef(), - terminal.publishedReleaseBundleDigest(), - release.publishWorkflowId(), - release.manifestHash(), - terminal.publicationVersionStateEpoch(), - operation.canonicalBytes(), - capture, - terminal.canonicalBytes(), - policies); - return new Fixture( - target, - new PublishedRealmEntryPolicySetEvidence( - target, - release.versionNumber(), - sourceBinding.commitId(), - "43", - release.publishedReleaseBundleRef(), - terminal.publishedReleaseBundleDigest(), - release.publishWorkflowId(), - release.manifestHash(), - terminal.publicationVersionStateEpoch(), - operation.canonicalBytes(), - capture, - terminal.canonicalBytes(), - policies.size(), - setDigest, - policies)); - } - - private static Source source( - String realm, boolean production, String policyId, String commitId, String revisionId) { - RealmEntryPolicy policy = - RealmEntryPolicy.parse( - "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," - + "\"realmSlug\":\"" - + realm - + "\",\"realmDisplayName\":\"" - + realm - + "\",\"visible\":true,\"publicProduction\":" - + production - + ",\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", - JSON); - return new Source(policyId, commitId, revisionId, policy); - } - - private static byte[] capture( - net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding operation, - DraftCommitBinding binding, - List sources) - throws IOException { - List> policies = - sources.stream() - .map( - source -> { - Map value = new LinkedHashMap<>(); - value.put("commitId", source.commitId()); - value.put("revisionId", source.revisionId()); - value.put("logicalRevisionId", "source-" + source.revisionId()); - value.put("policy", JSON.readTree(source.policy().canonicalJson())); - return value; - }) - .toList(); - Map snapshot = new LinkedHashMap<>(); - snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); - snapshot.put("bindingJson", binding.canonicalJson()); - snapshot.put("bindingDigest", binding.digest()); - snapshot.put("sourceEpoch", "43"); - snapshot.put("policies", policies); - byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); - ByteArrayOutputStream capture = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame( - capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); - DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); - DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); - return capture.toByteArray(); - } - - private static net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding - operation() throws Exception { - var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); - var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); - var draft = - DraftCommitBinding.fromStored( - new String(original.gameDesignBinding(), StandardCharsets.UTF_8), - original.inputDigest()); - var target = draft.target(); - String requestId = "publication-request"; - var selected = - AuthoredDraftPublishSelectionBinding.capture( - new AuthoredDraftPublishSelectionBinding.PublishIntent( - target.canonicalTenantId(), - target.canonicalVersionId(), - requestId, - "5", - "fixed-notes", - draft.requestId(), - draft.commitId(), - draft.digest()), - target, - draft, - new AuthoredDraftPublishSelectionBinding.VisibilityFence( - target, - draft.requestId(), - draft.commitId(), - draft.digest(), - "[]", - OffsetDateTime.parse("2026-10-07T00:00:00Z"))); - var account = - new AccountPublicationAuthorizationBinding( - UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), - UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), - new AccountPublicationAuthorizationBinding.PreallocationInput( - original.actorAccountId(), selected), - List.of( - new DraftAuthorizationFenceBinding.SourceEvidence( - DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, - original.actorAccountId().toString(), - "1", - "1", - null, - null, - new byte[] {1}))); - var request = seed.request(); - var world = - new WorldPublishedStartLocationEvidence( - new WorldPublishedStartLocationEvidence.Request( - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalVersionId(), - request.intakeRequestId(), - request.publicationFence(), - requestId, - selected.digest().substring(7), - 5L, - PublicationDigestRequestBinding.full( - target.canonicalTenantId().toString(), - Long.toString(target.gameDesignVersionRowId()), - requestId) - .derivedWorkflowIdentity(), - request.appliedCommitId(), - request.contentDigest(), - request.digestSchemaVersion(), - request.worldAffectedTuples()), - seed.selectorReceiptBytes(), - seed.originalAccountBindingBytes(), - seed.appliedResultBytes()); - return new GameDesignPublicationOperationBinding(account, world); - } - - private static ReleaseContent release( - net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding operation) { - var request = operation.world().request(); - var participants = - AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - owner.equals("GAME_LOGIC") ? DIGEST : null, - null, - null)) - .toList(); - return new ReleaseContent( - request.canonicalTenantId(), - request.canonicalVersionId(), - "bundle:exact", - 12, - "v2", - request.publishWorkflowId(), - DIGEST, - 1, - List.of( - new AuthoredWorldReleaseAttestationEvidence.Artifact( - "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), - List.of("asset-é"), - participants, - List.of("LOOK"), - "generation-1", - operation.world()); + private static PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture(boolean includeSide) + throws Exception { + return PublishedRealmEntryPolicySetEvidenceTest.fixture(includeSide); } - - private record Source( - String policyId, String commitId, String revisionId, RealmEntryPolicy policy) {} - - private record Fixture( - DraftCommitBinding.TargetProof target, PublishedRealmEntryPolicySetEvidence set) {} } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index 8c4be9e883..87cf140833 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -316,7 +316,7 @@ private static PublishedRealmEntryPolicySetEvidence copy( policies); } - private static Fixture fixture(boolean includeSide) throws Exception { + static Fixture fixture(boolean includeSide) throws Exception { GameDesignPublicationOperationBinding operation = operation(5L); var target = operation.account().input().selection().target(); var sourceBinding = operation.account().input().selection().selectedCommit(); @@ -620,7 +620,7 @@ private record Source( String logicalRevisionId, RealmEntryPolicy policy) {} - private record Fixture( + record Fixture( DraftCommitBinding.TargetProof target, GameDesignPublicationOperationBinding operation, DraftCommitBinding sourceBinding, From 48527adfbfb67459d3c48247a8c177a343d98b66 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:28:07 +1300 Subject: [PATCH 19/39] Apply canonical formatting to shared policy proof fixture --- .../common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java index f5930862a6..1da90617e0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java @@ -9,7 +9,6 @@ import java.util.UUID; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; -import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import org.junit.jupiter.api.Test; From 7e7830e1aba1497d19d57a6beb334bf704204345 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:36:48 +1300 Subject: [PATCH 20/39] test: assert complete actor assignment request schema --- .../world/PreseededActorAssignmentOwnerReadEvidenceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java index e74be61eae..0f9e35e1a9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java @@ -24,7 +24,7 @@ void assignmentRequestOmitsCountersAndResponseCarriesCountersOnlyFromOwnerProof( var request = evidence.request(); var wireRequest = PreseededActorAssignmentOwnerReadGrpcCodec.toRequest(request); - assertThat(wireRequest.getAllFields().keySet()) + assertThat(wireRequest.getDescriptorForType().getFields()) .noneMatch( field -> field.getName().contains("pointer") || field.getName().contains("epoch")); assertThat(PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(wireRequest)) From 23e7c4a318c9daacbd27596067a83beeb5469bad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:52:04 +1300 Subject: [PATCH 21/39] Unify launch evidence preimages and correct Account source fixture commits --- .../account-service/api-contracts.md | 1 + ...anonicalFirstJoinEventIntegrationTest.java | 15 ++-- ...AuthoredWorldLaunchDescriptorEvidence.java | 86 +------------------ ...oredWorldLaunchDescriptorEvidenceTest.java | 68 +++++++++++++++ 4 files changed, 81 insertions(+), 89 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 8b0e9fe9b7..3980a1dadd 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -117,6 +117,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. - `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. +- `ResolvePreseededActorStagingEligibility` – default-disabled, same-namespace Entity Management mTLS-only owner read limited to public-production actor staging; it returns staging evidence and creates no actor or gameplay admission. See [Preseeded actor-staging eligibility owner read](#preseeded-actor-staging-eligibility-owner-read). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index 347a202234..ca0cf0012f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -425,14 +425,15 @@ private void seedOwnerRowsAndOperation() { } private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { + DemoTenantEntitlementSnapshot created = + inTransaction( + () -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), null), tenantEvidence)); return inTransaction( - () -> { - DemoTenantEntitlementSnapshot created = - demoEntitlements.provision( - entitlementRequest(UUID.randomUUID(), null), tenantEvidence); - return demoEntitlements.provision( - entitlementRequest(UUID.randomUUID(), created), tenantEvidence); - }); + () -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), created), tenantEvidence)); } private DemoTenantEntitlementRequest entitlementRequest( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java index 5a6be36581..4f9c3aab1d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -245,90 +245,13 @@ public static AuthoredWorldLaunchDescriptorEvidence create( public static String requestDigest(Request request) { Objects.requireNonNull(request, "request"); - return digest( - REQUEST_DOMAIN, - field("schemaVersion", Integer.toString(SCHEMA_VERSION)), - field("targetNamespace", request.targetNamespace()), - field("controlPlaneRequestId", request.controlPlaneRequestId()), - field("canonicalTenantId", request.canonicalTenantId().toString()), - field("worldSlug", request.worldSlug()), - field( - "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), - field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), - field("gameTemplateId", Long.toString(request.gameTemplateId())), - optionalPresence( - "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), - optionalValue( - "requestedScriptPatchVersion", - request.requestedScriptPatchVersionPresent(), - request.requestedScriptPatchVersion()), - optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), - optionalValue( - "sourceVersionId", - request.sourceVersionIdPresent(), - decimal(request.sourceVersionId())), - optionalPresence("targetVersionId", request.targetVersionIdPresent()), - optionalValue( - "targetVersionId", - request.targetVersionIdPresent(), - decimal(request.targetVersionId())), - optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), - optionalValue( - "requestedRuntimeFlagsJson", - request.requestedRuntimeFlagsJsonPresent(), - request.requestedRuntimeFlagsJson())); + return digest(requestPreimage(request)); } /** Computes the result digest while deliberately excluding only {@code resultDigest}. */ public static String resultDigest(AuthoredWorldLaunchDescriptorEvidence evidence) { Objects.requireNonNull(evidence, "evidence"); - return digest( - RESULT_DOMAIN, - field("schemaVersion", Integer.toString(evidence.schemaVersion())), - field("targetNamespace", evidence.targetNamespace()), - field("controlPlaneRequestId", evidence.controlPlaneRequestId()), - field("canonicalTenantId", evidence.canonicalTenantId().toString()), - field("worldSlug", evidence.worldSlug()), - field( - "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), - field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), - field("gameTemplateId", Long.toString(evidence.gameTemplateId())), - optionalPresence( - "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), - optionalValue( - "requestedScriptPatchVersion", - evidence.requestedScriptPatchVersionPresent(), - evidence.requestedScriptPatchVersion()), - optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), - optionalValue( - "sourceVersionId", - evidence.sourceVersionIdPresent(), - decimal(evidence.sourceVersionId())), - optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), - optionalValue( - "targetVersionId", - evidence.targetVersionIdPresent(), - decimal(evidence.targetVersionId())), - optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), - optionalValue( - "requestedRuntimeFlagsJson", - evidence.requestedRuntimeFlagsJsonPresent(), - evidence.requestedRuntimeFlagsJson()), - field("requestDigest", evidence.requestDigest()), - field("launchDescriptorId", evidence.launchDescriptorId()), - field("versionId", Long.toString(evidence.versionId())), - optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), - optionalValue( - "scriptPatchVersion", - evidence.scriptPatchVersionPresent(), - evidence.scriptPatchVersion()), - field("runtimeFlagsJson", evidence.runtimeFlagsJson()), - field("generationConfigRevision", evidence.generationConfigRevision()), - field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), - field("releaseBundleId", Long.toString(evidence.releaseBundleId())), - field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), - optionalPresence("remapSetId", evidence.remapSetIdPresent()), - optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + return digest(resultPreimage(evidence)); } /** Returns the exact UTF-8 request preimage for shared producer and consumer proof. */ @@ -475,11 +398,10 @@ private static Field field(String name, String value) { return new Field(name, value); } - private static String digest(String domain, Field... fields) { + private static String digest(byte[] preimage) { try { return "sha256:" - + HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(domain, fields))); + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); } catch (NoSuchAlgorithmException exception) { throw new IllegalStateException("SHA-256 is unavailable", exception); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java new file mode 100644 index 0000000000..f2de396131 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldLaunchDescriptorEvidenceTest { + private static final String REQUEST_DIGEST = + "sha256:36ddbc22c1284986cc459dcf3737400bd24ba2b28a6cb8832001705bfe807ed9"; + private static final String RESULT_DIGEST = + "sha256:5205ddc44ac207017521c0782cdc21f69de1bdf4ccddefdf249211e05cfe3a3f"; + + @Test + void digestsHashTheExactPreimagesAndKeepTheirCurrentVectors() throws NoSuchAlgorithmException { + AuthoredWorldLaunchDescriptorEvidence.Request request = request(); + + assertThat(sha256(AuthoredWorldLaunchDescriptorEvidence.requestPreimage(request))) + .isEqualTo(REQUEST_DIGEST); + assertThat(request.requestDigest()).isEqualTo(REQUEST_DIGEST); + + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + Long.MAX_VALUE, + false, + null, + "{}", + "generation-config", + 9L, + 7L, + "published-release", + false, + null); + + assertThat(sha256(AuthoredWorldLaunchDescriptorEvidence.resultPreimage(evidence))) + .isEqualTo(RESULT_DIGEST); + assertThat(evidence.resultDigest()).isEqualTo(RESULT_DIGEST); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request() { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "synthetic-world", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static String sha256(byte[] preimage) throws NoSuchAlgorithmException { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } +} From 470540acfd153078dce8732ddcf6f4a44574aced Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:04:39 +1300 Subject: [PATCH 22/39] Reject malformed Unicode in initial admission request IDs --- .../WorldCanonicalInitialAdmissionHold.java | 2 ++ ...orldCanonicalInitialAdmissionHoldTest.java | 22 ++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java index 67c1e2408e..4f1a475da9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import tools.jackson.core.StreamReadFeature; import tools.jackson.databind.DeserializationFeature; import tools.jackson.databind.JsonNode; @@ -332,6 +333,7 @@ private static void requireBoundedText(String value, String field, int maximumCo || value.codePointCount(0, value.length()) > maximumCodePoints) { throw new IllegalArgumentException(field + " must be nonempty and bounded"); } + GameTenantCreationDigest.utf8ByteLength(value); } private static void requireLowerSha256(String value, String field) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java index 05404080d2..bd974c753e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java @@ -42,6 +42,22 @@ void emitsLiteralCanonicalVectorsForBothApprovedOrigins() { .isNotEqualTo("sha256:" + noPrior.initialAdmissionRequestDigest()); } + @Test + void rejectsUnpairedSurrogatesAtRequestConstruction() { + assertThatThrownBy(() -> noPriorRequest("gs-initial-admission-" + (char) 0xd800)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> noPriorRequest("gs-initial-admission-" + (char) 0xdc00)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsSupplementaryCodePointAndRoundTripsCanonicalRequest() { + String requestId = "gs-initial-admission-" + new String(Character.toChars(0x1f680)); + Request request = noPriorRequest(requestId); + + assertThat(Request.fromStored(request.canonicalRequestBytes())).isEqualTo(request); + } + @Test void requestAndAcquiredIdentityRoundTripAndExactRetryKeepTheirCanonicalIdentity() { Request noPrior = noPriorRequest(); @@ -457,6 +473,10 @@ void parserRejectsInvalidUuidsOptionalRepresentationsCountersAliasesAndUnknownIn } private static Request noPriorRequest() { + return noPriorRequest("gs-initial-admission-17"); + } + + private static Request noPriorRequest(String requestId) { return request( "prod", TENANT, @@ -466,7 +486,7 @@ private static Request noPriorRequest() { GAME_INSTANCE, VERSION, 7L, - "gs-initial-admission-17", + requestId, REQUEST_DIGEST, InitialAdmissionOrigin.NO_PRIOR_POINTER, 12L, From 9ba8dd84669adeb6b0c4c01cbbd09bb50fc9d0b5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:21:10 +1300 Subject: [PATCH 23/39] Bind canonical JOIN publication to current entitlement and strengthen evidence values --- design/project-management/ai-observations.md | 6 + ...countMembershipAuthorityEventProducer.java | 39 ++- ...ingEligibilityPostgresIntegrationTest.java | 10 +- ...anonicalFirstJoinEventIntegrationTest.java | 71 +++--- .../dto/TenantAuthorityEventV1CodecTest.java | 13 +- ...thorityEventProducerCanonicalJoinTest.java | 230 +++++++++++++++++- .../DraftAuthorizationFenceBinding.java | 36 +++ ...DesignPublicationTerminalReadEvidence.java | 12 + .../PublishedRealmEntryPolicySetEvidence.java | 5 +- ...eededActorAssignmentOwnerReadEvidence.java | 3 + .../WorldDraftTerminalReadGrpcCodecTest.java | 66 +++++ ...dActorAssignmentOwnerReadEvidenceTest.java | 42 ++++ ...lishedRealmEntryPolicySetEvidenceTest.java | 24 ++ 13 files changed, 505 insertions(+), 52 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 75133bf080..656dfe5d79 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -74,3 +74,9 @@ Entry format: - Expected pattern: Verify the absolute worktree, branch, head, and relevant status before editing; use absolute paths in every patch header and verify the first write in the assigned checkout. A shell command's working directory does not establish a separate patch tool's destination. Preserve before-images when an assigned path already contains uncommitted work. - Current status: The helper corrected all owned targets. Only 37 confirmed new wrong-checkout paths were removed after verifying identical receiver and owned-target copies; the 16 uncertain paths remain untouched for independent recovery assessment. Matching the newly written bytes does not prove prior contents survived. Exact paths and evidence are retained in the controller inbox and active job, not another ledger. - Reconsideration trigger: Close the uncertain recovery only after a trusted before-image or the owning human establishes the previous content; do not infer preservation from hashes of replacement copies. + +- `2026-10-09`: Credential screening can reject ordinary authentication prose + - Context: A guarded Gameplay job-brief update was rejected as credential material even though it contained only implementation and proof status. + - Observation: The strict screening rule interpreted the ordinary phrase `no-bearer dispatch` as a bearer credential. The prior brief remained intact; a checkpoint succeeded, and rephrasing the description as workload-only dispatch allowed the guarded update. + - Expected pattern: Preserve the rejected update and prior brief, report the non-secret triggering phrase without raw credential material, and use field/category/line diagnostics to distinguish prose from accidental disclosure. Do not disable screening or bypass the controller. + - Current status: The corrected brief is saved. Overseer reports merged #3116 now supplies the diagnostic location while preserving the strict detector. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 529bceb663..3a4c21af14 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -24,6 +25,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -62,6 +64,7 @@ public class AccountMembershipAuthorityEventProducer { private final AccountAuthorityOutboxRepository authorityOutboxRepository; private final AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository; private final AccountTenantAuthorityEventRepository tenantAuthorityEventRepository; + private final AccountDemoTenantEntitlementRepository demoTenantEntitlementRepository; @SuppressFBWarnings( value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, @@ -77,7 +80,8 @@ public AccountMembershipAuthorityEventProducer( AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository, - AccountTenantAuthorityEventRepository tenantAuthorityEventRepository) { + AccountTenantAuthorityEventRepository tenantAuthorityEventRepository, + AccountDemoTenantEntitlementRepository demoTenantEntitlementRepository) { this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository); this.accountRepository = Objects.requireNonNull(accountRepository); this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); @@ -87,6 +91,7 @@ public AccountMembershipAuthorityEventProducer( this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository); this.sourceEvidenceRepository = Objects.requireNonNull(sourceEvidenceRepository); this.tenantAuthorityEventRepository = Objects.requireNonNull(tenantAuthorityEventRepository); + this.demoTenantEntitlementRepository = Objects.requireNonNull(demoTenantEntitlementRepository); } /** @@ -187,6 +192,9 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( membership, provenance, tenantSourceEvent); + DemoTenantEntitlementSnapshot entitlementSnapshot = + demoTenantEntitlementRepository.readCurrent(tenantUuid); + requireCurrentJoinEntitlement(operation, entitlementSnapshot, tenantSourceEvent, tenantUuid); if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { throw new IllegalStateException( "Canonical first JOIN cannot publish over retained membership-event history"); @@ -520,6 +528,35 @@ private static void requireOperationMatchesRequest( } } + private static void requireCurrentJoinEntitlement( + CanonicalJoinOperationEvidence operation, + DemoTenantEntitlementSnapshot entitlement, + TenantAuthorityEventV1Codec.Event tenantSourceEvent, + UUID tenantUuid) { + if (entitlement == null + || !tenantUuid.equals(entitlement.canonicalTenantId()) + || entitlement.entitlementVersion() != operation.entitlementVersion() + || !entitlement.allowPublicJoin() + || !entitlement.gameplayAvailable() + || tenantSourceEvent == null + || !tenantUuid.equals(tenantSourceEvent.tenantId()) + || !entitlement.sourceEvidence().equals(tenantSourceEvent.sourceEvidence()) + || entitlement.tenantAuthorityGeneration() != tenantSourceEvent.tenantAuthorityGeneration() + || entitlement.tenantAuthoritySourceVersion() + != tenantSourceEvent.tenantAuthoritySourceVersion() + || !entitlement.tenantAuthorityOutboxStreamKey().equals(tenantSourceEvent.outboxStreamKey()) + || entitlement.tenantAuthorityOutboxSequence() != tenantSourceEvent.outboxSequence() + || !entitlement.tenantAuthorityEventId().equals(tenantSourceEvent.eventId()) + || !entitlement.tenantAuthorityEventDigest().equals(tenantSourceEvent.eventDigest()) + || !entitlement.outboxStreamKey().equals(tenantSourceEvent.tenantBillingStreamKey()) + || entitlement.tenantBillingSequence() != tenantSourceEvent.tenantBillingSequence() + || !entitlement.eventId().equals(tenantSourceEvent.tenantBillingEventId()) + || !entitlement.eventDigest().equals(tenantSourceEvent.tenantBillingEventDigest())) { + throw new IllegalStateException( + "Canonical first JOIN requires exact current public-join entitlement evidence"); + } + } + private static List requireFirstJoinRoleSnapshot( CanonicalJoinScopeV2 scope, AccountTenantMembership membership, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java index 0ee66e66ff..83af23aad0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java @@ -268,7 +268,8 @@ dsl, new LegacyTenantSourceEvidence(dsl), TEST_NAMESPACE), generations, outbox, sourceEvidence, - tenantEvents); + tenantEvents, + entitlements); seedMembershipOperation(); } @@ -314,8 +315,13 @@ private void seedMembershipOperation() { account.getAccountUuid(), tenantUuid)); connectScopes.insertCanonical(account.getId(), scope, tenantProvenance); joinOperations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + DemoTenantEntitlementSnapshot currentEntitlement = entitlements.readCurrent(tenantUuid); joinOperations.bindCanonicalPolicyEvidence( - joinRequestId, scope, callerBinding, true, 5L); + joinRequestId, + scope, + callerBinding, + currentEntitlement.allowPublicJoin(), + currentEntitlement.entitlementVersion()); }); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index ca0cf0012f..d72151f370 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -114,7 +114,12 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { assertThat(decoded.membershipAuthorityGeneration()).isEqualTo("1"); assertThat(decoded.authorityTuple().privateRealmGrantVersions()).isEmpty(); assertThat(decoded.authorityTuple().accountSecurityCutoff()).isEmpty(); - assertThat(decoded.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(decoded.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + fixture.tenantUuid.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "2", "1", "account:auth-authority:v1:tenant/" + fixture.tenantUuid, "1"))); assertThat(decoded.roles()).containsExactly("player"); assertThat(pair.membershipExists()).isTrue(); assertThat(pair.membershipVersion()).isEqualTo(2L); @@ -142,41 +147,39 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { } @Test - void laterTenantAuthorityUsesTheCurrentAccountSourceEventAndItsExactBillingCutoff() { + void changedEntitlementPreventsAStalePendingJoinFromCommittingMembership() { Fixture fixture = newFixture(); DemoTenantEntitlementSnapshot entitlement = fixture.provisionCurrentTenantEntitlement(); - var proof = fixture.commitFirstJoin(); + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); String stream = fixture.membershipStream(); - AccountAuthorityOutboxRepository.Event membershipEvent = - fixture.inTransaction( - () -> fixture.outbox.findEvent(stream, proof.eventSequence()).orElseThrow()); - var decoded = - MembershipAuthorityEventV1Codec.verify( - new String(membershipEvent.payload(), StandardCharsets.UTF_8)); var currentTenantEvent = fixture.inTransaction( () -> fixture.tenantAuthorityEvents.readCurrentByTenant(fixture.tenantUuid)); - + var pendingOperation = + fixture.inTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + return fixture.operations.findCanonicalEvidenceForUpdateByRequestId( + fixture.requestId); + }); + + assertThat(entitlement.entitlementVersion()).isEqualTo(2L); + assertThat(pendingOperation).isPresent(); + assertThat(pendingOperation.orElseThrow().status()).isEqualTo("PENDING"); + assertThat(pendingOperation.orElseThrow().entitlementVersion()).isEqualTo(1L); assertThat(entitlement.tenantAuthorityGeneration()).isEqualTo(3L); assertThat(entitlement.tenantAuthoritySourceVersion()).isEqualTo(3L); assertThat(entitlement.tenantBillingSequence()).isEqualTo(2L); assertThat(entitlement.tenantAuthorityOutboxSequence()).isEqualTo(2L); - assertThat(decoded.authorityTuple().tenantAuthorityGeneration()) - .isEqualTo(Map.of(fixture.tenantUuid.toString(), "3")); - assertThat(decoded.authorityTuple().tenantBillingCutoff()) - .contains( - Map.of( - fixture.tenantUuid.toString(), - new MembershipAuthorityEventV1Codec.TenantBillingCutoff( - "3", "2", currentTenantEvent.outboxStreamKey(), "2"))); assertThat(currentTenantEvent.tenantBillingEventId()).isEqualTo(entitlement.eventId()); assertThat(currentTenantEvent.tenantBillingEventDigest()).isEqualTo(entitlement.eventDigest()); - assertThat(decoded.eventId()).isEqualTo(proof.eventId()); assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) - .isEqualTo(1L); + .isZero(); assertThat(fixture.count("account_authority_outbox_events", "outbox_stream_key", stream)) - .isEqualTo(1L); + .isZero(); } @Test @@ -382,7 +385,8 @@ private Fixture(TestContext context) { generations, outbox, sourceEvidence, - tenantAuthorityEvents); + tenantAuthorityEvents, + demoEntitlements); this.terminalCoordinator = new AccountCanonicalFirstJoinTerminalCoordinator( accounts, operations, memberships, roles, outbox, pairs, auditOutbox, producer); @@ -419,21 +423,32 @@ private void seedOwnerRowsAndOperation() { account.getAccountUuid(), tenantUuid)); connectScopes.insertCanonical(account.getId(), scope, provenance); operations.insertCanonicalIntent(requestId, scope, callerBinding); - operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 5L); return null; }); - } - - private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { - DemoTenantEntitlementSnapshot created = + DemoTenantEntitlementSnapshot currentEntitlement = inTransaction( () -> demoEntitlements.provision( entitlementRequest(UUID.randomUUID(), null), tenantEvidence)); + inTransaction( + () -> { + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + callerBinding, + currentEntitlement.allowPublicJoin(), + currentEntitlement.entitlementVersion()); + return null; + }); + } + + private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { + DemoTenantEntitlementSnapshot current = + inTransaction(() -> demoEntitlements.readCurrent(tenantUuid)); return inTransaction( () -> demoEntitlements.provision( - entitlementRequest(UUID.randomUUID(), created), tenantEvidence)); + entitlementRequest(UUID.randomUUID(), current), tenantEvidence)); } private DemoTenantEntitlementRequest entitlementRequest( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java index e783f4c871..efa0c912de 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java @@ -53,10 +53,15 @@ void authorityEventKeepsItsCanonicalCheckpointSeparateFromBillingReceipt() { .contains("\"tenantAuthorityGeneration\":\"2\"") .contains("\"tenantBillingSequence\":\"1\""); - byte[] altered = authorityEvent.payload(); - altered[altered.length - 2] = altered[altered.length - 2] == 'a' ? (byte) 'b' : (byte) 'a'; - assertThatThrownBy(() -> TenantAuthorityEventV1Codec.verify(altered)) - .isInstanceOf(IllegalArgumentException.class); + String alteredJson = + new String(authorityEvent.payload(), StandardCharsets.UTF_8) + .replace("\"tenantAuthorityGeneration\":\"2\"", "\"tenantAuthorityGeneration\":\"3\""); + assertThat(alteredJson) + .isNotEqualTo(new String(authorityEvent.payload(), StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> TenantAuthorityEventV1Codec.verify(alteredJson.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest or canonical bytes differ"); } private static FreshTenantCreationEvidence source(UUID tenantId) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 38b7c36b92..1a57bcfa16 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; @@ -44,6 +45,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; @@ -95,6 +97,12 @@ void clearTransactionState() { void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { Fixture fixture = new Fixture(); fixture.arrangePendingFirstJoin(); + DemoTenantEntitlementSnapshot currentEntitlement = + fixture.entitlementSnapshot(fixture.currentTenantEvent()); + assertThat(currentEntitlement.entitlementVersion()).isEqualTo(5L); + assertThat(currentEntitlement.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(currentEntitlement.entitlementVersion()) + .isNotEqualTo(currentEntitlement.tenantAuthorityGeneration()); AtomicReference committedEvent = new AtomicReference<>(); AtomicInteger membershipCheckpointReads = new AtomicInteger(); when(fixture.outbox.readCheckpoint(any(String.class))) @@ -151,10 +159,16 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { assertThat(event.roles()).containsExactly("player"); assertThat(event.issuanceFence()).isEqualTo("1"); assertThat(event.authorityTuple().tenantAuthorityGeneration()) - .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); + .isEqualTo(Map.of(TENANT_UUID.toString(), "2")); assertThat(event.authorityTuple().accountSecurityCutoff()).isEmpty(); - assertThat(event.authorityTuple().tenantBillingCutoff()).isEmpty(); - verifyNoInteractions(fixture.tenantAuthorityEvents); + assertThat(event.authorityTuple().tenantBillingCutoff()) + .contains( + Map.of( + TENANT_UUID.toString(), + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + "2", "1", "account:auth-authority:v1:tenant/" + TENANT_UUID, "1"))); + verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); + verify(fixture.entitlements).readCurrent(TENANT_UUID); var order = inOrder(fixture.accounts, fixture.joinOperations, fixture.memberships); order.verify(fixture.accounts).findByAccountUuid(ACCOUNT_UUID); @@ -192,6 +206,8 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() : Optional.empty()); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)).thenReturn(Optional.of(event)); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)).thenReturn(Optional.of(event)); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenThrow(new IllegalStateException("current entitlement is no longer available")); fixture.startWritableTransaction(); Checkpoint replay = @@ -206,6 +222,7 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() .readCompositeSnapshot( "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID)); verifyNoInteractions(fixture.sourceEvidence); + verify(fixture.entitlements, never()).readCurrent(TENANT_UUID); } @Test @@ -214,7 +231,7 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { fixture.arrangePendingFirstJoin(); when(fixture.authority.readCompositeSnapshot( "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) - .thenReturn(fixture.authoritySnapshot(3L, 3L, 1L, 1L)); + .thenReturn(fixture.authoritySnapshot(3L, 3L, 2L, 1L)); when(fixture.sourceEvidence.readCurrentIssuerAccountSources( "firemud-account-service", ACCOUNT_UUID)) .thenReturn(fixture.sourceSnapshot(3L, 3L)); @@ -269,7 +286,7 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { assertThat(event.authorityTuple().issuerAuthGeneration()).isEqualTo("3"); assertThat(event.authorityTuple().accountAuthorityGeneration()).isEqualTo("3"); assertThat(event.authorityTuple().tenantAuthorityGeneration()) - .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); + .isEqualTo(Map.of(TENANT_UUID.toString(), "2")); assertThat(event.authorityTuple().membershipAuthorityGeneration()) .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); assertThat(event.issuanceFence()).isEqualTo("3"); @@ -295,6 +312,8 @@ void firstJoinAcceptsLaterTenantAuthorityOnlyWithExactCurrentTenantSourceAndBill tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 9L, 7L); when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)) .thenReturn(tenantSourceEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(tenantSourceEvent)); fixture.startWritableTransaction(); AtomicReference committedEvent = new AtomicReference<>(); @@ -349,6 +368,117 @@ void firstJoinAcceptsLaterTenantAuthorityOnlyWithExactCurrentTenantSourceAndBill verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); } + @Test + void firstJoinDeniesAStalePendingEntitlementVersionWithoutMutation() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event currentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L, 6L, true, true); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(currentEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(currentEvent, 6L, true, true)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesCurrentEntitlementWhenPublicJoinIsNoLongerAllowed() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event currentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L, 5L, true, false); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(currentEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(currentEvent, 5L, true, false)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesCurrentEntitlementWhenGameplayIsUnavailable() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event currentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L, 5L, false, true); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(currentEvent); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(currentEvent, 5L, false, true)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinFailsClosedWhenCurrentEntitlementReadIsUnavailable() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenThrow(new IllegalStateException("current entitlement unavailable")); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("current entitlement unavailable"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + + @Test + void firstJoinDeniesEntitlementSnapshotWithDifferentCurrentAuthorityEventBinding() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + TenantAuthorityEventV1Codec.Event differentCurrentEvent = + tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 9L, 1L); + when(fixture.entitlements.readCurrent(TENANT_UUID)) + .thenReturn(fixture.entitlementSnapshot(differentCurrentEvent)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current public-join entitlement evidence"); + + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + @Test void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { Fixture fixture = new Fixture(); @@ -359,6 +489,7 @@ void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { when(fixture.sourceEvidence.readCurrentIssuerAccountSources( "firemud-account-service", ACCOUNT_UUID)) .thenReturn(fixture.sourceSnapshot(3L, 3L)); + when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(null); fixture.startWritableTransaction(); assertThatThrownBy( @@ -540,6 +671,28 @@ private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( long tenantSourceVersion, long authorityOutboxSequence, long billingSequence) { + return tenantAuthorityEvent( + tenantUuid, + sourceOperationId, + tenantGeneration, + tenantSourceVersion, + authorityOutboxSequence, + billingSequence, + 5L, + true, + true); + } + + private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( + UUID tenantUuid, + UUID sourceOperationId, + long tenantGeneration, + long tenantSourceVersion, + long authorityOutboxSequence, + long billingSequence, + long entitlementVersion, + boolean gameplayAvailable, + boolean allowPublicJoin) { FreshTenantCreationEvidence source = freshTenantEvidence(tenantUuid, sourceOperationId); UUID entitlementRequestId = UUID.nameUUIDFromBytes( @@ -556,17 +709,22 @@ private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( tenantUuid, source.creationRequestId(), source.requestDigest(), - 1L, - 1L, - 1L, - true, - true, + entitlementVersion - 1L, + tenantGeneration - 1L, + tenantSourceVersion - 1L, + gameplayAvailable, + allowPublicJoin, false, false, new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); var billingEvent = DemoTenantEntitlementEventV1Codec.seal( - request, source, 2L, tenantGeneration, tenantSourceVersion, billingSequence); + request, + source, + entitlementVersion, + tenantGeneration, + tenantSourceVersion, + billingSequence); return TenantAuthorityEventV1Codec.seal( request, source, @@ -637,6 +795,8 @@ private static final class Fixture { mock(AccountAuthoritySourceEvidenceRepository.class); private final AccountTenantAuthorityEventRepository tenantAuthorityEvents = mock(AccountTenantAuthorityEventRepository.class); + private final AccountDemoTenantEntitlementRepository entitlements = + mock(AccountDemoTenantEntitlementRepository.class); private final AccountMembershipAuthorityEventProducer producer = new AccountMembershipAuthorityEventProducer( joinOperations, @@ -647,7 +807,8 @@ private static final class Fixture { authority, outbox, sourceEvidence, - tenantAuthorityEvents); + tenantAuthorityEvents, + entitlements); private final CanonicalJoinScopeV2 scope = scopeValue(); private final VerifiedTenantProvenance provenance = provenanceValue(); private final Account account = accountValue(); @@ -670,9 +831,52 @@ private void arrangePendingFirstJoin() { .thenReturn(authoritySnapshot()); when(sourceEvidence.readCurrentIssuerAccountSources("firemud-account-service", ACCOUNT_UUID)) .thenReturn(freshSourceSnapshot()); + TenantAuthorityEventV1Codec.Event tenantEvent = currentTenantEvent(); + when(tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(tenantEvent); + when(entitlements.readCurrent(TENANT_UUID)).thenReturn(entitlementSnapshot(tenantEvent)); when(outbox.readCheckpoint(any(String.class))).thenReturn(Optional.empty()); } + private TenantAuthorityEventV1Codec.Event currentTenantEvent() { + return tenantAuthorityEvent(TENANT_UUID, TENANT_OPERATION_ID, 2L, 2L, 1L, 1L); + } + + private DemoTenantEntitlementSnapshot entitlementSnapshot( + TenantAuthorityEventV1Codec.Event event) { + return entitlementSnapshot(event, 5L, true, true); + } + + private DemoTenantEntitlementSnapshot entitlementSnapshot( + TenantAuthorityEventV1Codec.Event event, + long entitlementVersion, + boolean gameplayAvailable, + boolean allowPublicJoin) { + return new DemoTenantEntitlementSnapshot( + TENANT_UUID, + event.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + gameplayAvailable, + allowPublicJoin, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L), + entitlementVersion, + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingStreamKey(), + event.tenantBillingSequence(), + event.tenantBillingEventId(), + event.tenantBillingEventDigest(), + event.tenantBillingEventDigest(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + } + private IssuerAccountSourceSnapshot freshSourceSnapshot() { return sourceSnapshot(1L, 1L); } @@ -797,7 +1001,7 @@ private String expectedEventId() { } private CompositeSnapshot authoritySnapshot() { - return authoritySnapshot(1L, 1L, 1L, 1L); + return authoritySnapshot(1L, 1L, 2L, 1L); } private CompositeSnapshot authoritySnapshot( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java index ece7e54a82..0cb9a3357d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java @@ -301,6 +301,18 @@ public byte[] canonicalBytes() { return output.toByteArray(); } + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftAuthorizationFenceBinding binding + && Arrays.equals(canonicalBytes(), binding.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + public enum SourceKind { ISSUER, ACCOUNT, @@ -385,6 +397,18 @@ public byte[] canonicalBytes() { return output.toByteArray(); } + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof SourceEvidence source + && Arrays.equals(canonicalBytes(), source.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + /** Decodes only the exact immutable framing written by this source owner. */ public static SourceEvidence fromStored(byte[] stored) { FrameReader reader = new FrameReader(stored); @@ -581,6 +605,18 @@ public byte[] canonicalBytes() { return output.toByteArray(); } + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof OwnerReadback readback + && Arrays.equals(canonicalBytes(), readback.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + private static String readbackSchema(DraftAuthorizationFenceBinding binding) { return SCHEMA_V1.equals(binding.schemaVersion()) ? OWNER_READBACK_SCHEMA_V1 diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java index d88b0fdb69..2d87c8a951 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java @@ -73,6 +73,18 @@ public byte[] canonicalBytes() { return out.toByteArray(); } + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof ReadRequest request + && Arrays.equals(canonicalBytes(), request.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + public static ReadRequest fromStored(byte[] bytes) { var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); r.expect(SCHEMA); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java index 2bfa51ccf9..4a2a66354a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -499,10 +499,7 @@ private static CapturedSource parseCapture(byte[] bytes, byte[] expectedOperatio byte[] operationBytes = capture.bytes(); byte[] snapshotBytes = capture.bytes(); capture.requireEnd(); - if (!Arrays.equals(operationBytes, expectedOperationBytes) - || !Arrays.equals( - operationBytes, - GameDesignPublicationOperationBinding.fromStored(operationBytes).canonicalBytes())) { + if (!Arrays.equals(operationBytes, expectedOperationBytes)) { throw new IllegalArgumentException("Captured source operation bytes changed"); } String snapshotJson = strictUtf8(snapshotBytes); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java index e4a1d6289a..adaa21cf3c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidence.java @@ -46,6 +46,9 @@ public static CanonicalGameplayRosterOwnerReadEvidence.Request sourceRequest( Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { Objects.requireNonNull(request, "request"); Objects.requireNonNull(proof, "proof"); + if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + throw new IllegalArgumentException("Committed Game Session owner proof required"); + } var hold = proof.holdIdentity().request(); return new CanonicalGameplayRosterOwnerReadEvidence.Request( request.assignmentUuid(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index 35bf6e7387..649e3bbf8c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -8,6 +8,7 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -59,6 +60,71 @@ void requestCarriesAndDefensivelyRetainsTheCompleteOriginalBinding() { .isNotEqualTo(request.accountBinding().operationId()); } + @Test + void independentlyDecodedByteEvidenceUsesCanonicalValueEquality() { + var request = request(); + var binding = request.accountBinding(); + var decodedBinding = DraftAuthorizationFenceBinding.fromStored(binding.canonicalBytes()); + assertThat(decodedBinding).isEqualTo(binding); + assertThat(decodedBinding.hashCode()).isEqualTo(binding.hashCode()); + assertThat(new HashSet<>(List.of(binding, decodedBinding))).hasSize(1); + + var source = binding.sources().getFirst(); + var decodedSource = SourceEvidence.fromStored(source.canonicalBytes()); + assertThat(decodedSource).isEqualTo(source); + assertThat(decodedSource.hashCode()).isEqualTo(source.hashCode()); + assertThat(new HashSet<>(List.of(source, decodedSource))).hasSize(1); + + var changedSource = + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {9}); + assertThat(changedSource).isNotEqualTo(source); + var changedSourceBinding = + new DraftAuthorizationFenceBinding( + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + binding.expectedDraftEpoch(), + binding.gameDesignBinding(), + binding.normalizedInput(), + binding.inputDigest(), + List.of(changedSource), + binding.schemaVersion(), + binding.requiredOwners()); + assertThat(changedSourceBinding).isNotEqualTo(binding); + + var readback = committedReadback(request); + var decodedReadback = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(readback.canonicalBytes()); + assertThat(decodedReadback).isEqualTo(readback); + assertThat(decodedReadback.hashCode()).isEqualTo(readback.hashCode()); + assertThat(new HashSet<>(List.of(readback, decodedReadback))).hasSize(1); + assertThat( + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + readback.operationId(), + readback.commitId(), + readback.fenceId(), + readback.inputDigest(), + readback.fullBinding(), + new byte[] {9}) + .canonicalBytes())) + .isNotEqualTo(readback); + } + @Test void unknownIsExplicitAndCarriesNoOwnerResult() { var request = request(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java index 0f9e35e1a9..596f5dc9ee 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java @@ -115,6 +115,48 @@ void rejectsChangedSelectorsPolicyReleaseUnknownFieldsAndPartialSourceEvidence() .isInstanceOf(IllegalArgumentException.class); } + @Test + void sourceRequestRequiresCommittedOwnerProofBeforeReadingCommittedPointer() throws Exception { + var evidence = fixture(); + var source = evidence.sourceEvidence(); + var committed = source.gameSessionOwnerProof(); + assertThat( + PreseededActorAssignmentOwnerReadEvidence.sourceRequest(evidence.request(), committed)) + .isEqualTo(source.request()); + + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + committed.holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadEvidence.sourceRequest( + evidence.request(), pending)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Committed Game Session owner proof"); + + var aborted = + new GameSessionCanonicalInitialAdmissionOwnerProof( + committed.holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + "sha256:" + "c".repeat(64), + true, + TERMINAL_AT); + assertThatThrownBy( + () -> + PreseededActorAssignmentOwnerReadEvidence.sourceRequest( + evidence.request(), aborted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Committed Game Session owner proof"); + } + private static PreseededActorAssignmentOwnerReadEvidence fixture() throws Exception { var policySet = PublishedRealmEntryPolicySetEvidenceTest.preseededSetFixture(); var selectedPolicy = policySet.policies().getFirst(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index 87cf140833..547ca56002 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -40,6 +41,29 @@ static PublishedRealmEntryPolicySetEvidence preseededSetFixture() throws Excepti return fixture(false).set(); } + @Test + void terminalReadRequestUsesCanonicalByteValueEquality() throws Exception { + var fixture = fixture(false); + var expected = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + fixture.operation().world().request().targetNamespace(), + uuid("10101010-1010-4010-8010-101010101010"), + fixture.operation().canonicalBytes()); + var decoded = ReadRequest.fromStored(expected.canonicalBytes()); + + assertThat(decoded).isEqualTo(expected); + assertThat(decoded.hashCode()).isEqualTo(expected.hashCode()); + assertThat(new java.util.HashSet<>(List.of(expected, decoded))).hasSize(1); + var changedIdentity = + new ReadRequest( + expected.schemaVersion(), + expected.targetNamespace(), + uuid("20202020-2020-4020-8020-202020202020"), + expected.operationBytes()); + assertThat(changedIdentity).isNotEqualTo(expected); + } + @Test void completeSetRetainsTheActualOperationCaptureTerminalAndOrderedSourceRows() throws Exception { Fixture fixture = fixture(false); From b5234acd7f93440170178d1b808e19b4a00ac644 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:35:27 +1300 Subject: [PATCH 24/39] Clarify current entitlement and credential screening proof limits --- design/project-management/ai-observations.md | 3 ++- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 656dfe5d79..7c049b6178 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -79,4 +79,5 @@ Entry format: - Context: A guarded Gameplay job-brief update was rejected as credential material even though it contained only implementation and proof status. - Observation: The strict screening rule interpreted the ordinary phrase `no-bearer dispatch` as a bearer credential. The prior brief remained intact; a checkpoint succeeded, and rephrasing the description as workload-only dispatch allowed the guarded update. - Expected pattern: Preserve the rejected update and prior brief, report the non-secret triggering phrase without raw credential material, and use field/category/line diagnostics to distinguish prose from accidental disclosure. Do not disable screening or bypass the controller. - - Current status: The corrected brief is saved. Overseer reports merged #3116 now supplies the diagnostic location while preserving the strict detector. + - Current status: The corrected brief is saved. Overseer reports merged #3116 now supplies the diagnostic location while preserving the strict detector; ordinary authentication prose can still trigger false positives. + - Reconsideration trigger: revisit if an authorized guarded update shows that location diagnostics do not make an ordinary-prose false positive actionable; any detector refinement must preserve strict credential screening. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 82647106be..5304edf7eb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. -Canonical first-JOIN membership-event production preserves the exact fresh tenant 1/1 baseline and permits later tenant authority only after Account's current typed tenant event, fresh Game Design provenance, and both composite generation/source-version values match. The event carries the linked tenant billing cutoff from those source coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Consolidated validation passed 593 Account unit cases, five shared World hold cases, jOOQ generation, and integration-test compilation. Current PostgreSQL-backed integration sources, including the new later-generation JOIN case, compiled but were unrun locally. An earlier hosted Account run executed 74 integration cases and found four fixture failures; their corrections are present, but this current head still requires exact-head hosted proof. +Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Consolidated validation passed 593 Account unit cases, five shared World hold cases, jOOQ generation, and integration-test compilation. Current PostgreSQL-backed integration sources, including the new later-generation JOIN case, compiled but were unrun locally. An earlier hosted Account run executed 74 integration cases and found four fixture failures; their corrections are present, but this current head still requires exact-head hosted proof. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. From ef41f7d1ab6c2df889ebe4b421b5707ded882b17 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:09:18 +1300 Subject: [PATCH 25/39] Clarify writable owner transactions for locked admission reads --- ...ccountDemoTenantEntitlementRepository.java | 18 +++++++++--- ...AccountTenantAuthorityEventRepository.java | 9 ++++-- ...untTenantAuthorityEventRepositoryTest.java | 28 +++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java index 77d1cabbaf..6c8c3bb44b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -165,8 +165,13 @@ public DemoTenantEntitlementSnapshot provision( return snapshot(committedEvent, authorityEvent); } - /** Reads one exact current snapshot and denies stale or incomplete Account/source state. */ - @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + /** + * Reads one exact current snapshot and denies stale or incomplete Account/source state. + * + *

Requires the caller's writable Account owner transaction; MANDATORY does not convert an + * existing read-only transaction into a writable one. + */ + @Transactional(propagation = Propagation.MANDATORY) public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { requireTenantUuid(canonicalTenantId); Optional evidence = @@ -188,8 +193,13 @@ public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { return snapshot(current.billingEvent(), current.authorityEvent()); } - /** Re-reads all source, generation, version, and outbox evidence at the final admission fence. */ - @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + /** + * Re-reads all source, generation, version, and outbox evidence at the final admission fence. + * + *

Requires the caller's writable Account owner transaction; MANDATORY does not convert an + * existing read-only transaction into a writable one. + */ + @Transactional(propagation = Propagation.MANDATORY) public DemoTenantEntitlementSnapshot revalidate(DemoTenantEntitlementSnapshot evaluated) { Objects.requireNonNull(evaluated, "Complete evaluated entitlement evidence is required"); DemoTenantEntitlementSnapshot current = readCurrent(evaluated.canonicalTenantId()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index 60655921ca..16356348d0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -382,8 +382,13 @@ public Event readCurrentCheckpoint( eventDigest); } - /** Resolves current Account owner state itself; callers cannot supply a receipt or checkpoint. */ - @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + /** + * Resolves current Account owner state itself; callers cannot supply a receipt or checkpoint. + * + *

Requires the caller's writable Account owner transaction; MANDATORY does not convert an + * existing read-only transaction into a writable one. + */ + @Transactional(propagation = Propagation.MANDATORY) public Event readCurrentByTenant(UUID tenantId) { requireTransaction(); requireTenant(tenantId); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java index bd2a21e841..380b9b3146 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -9,15 +9,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.lang.reflect.Method; import java.util.UUID; import java.util.function.LongFunction; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; @@ -27,6 +30,8 @@ import org.jooq.Record; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountTenantAuthorityEventRepositoryTest { @@ -39,6 +44,18 @@ class AccountTenantAuthorityEventRepositoryTest { UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String SOURCE_REQUEST_DIGEST = "sha256:" + "a".repeat(64); + @Test + void finalAdmissionOwnerReadsRequireWritableMandatoryTransactions() throws NoSuchMethodException { + assertWritableMandatory( + AccountDemoTenantEntitlementRepository.class, "readCurrent", UUID.class); + assertWritableMandatory( + AccountDemoTenantEntitlementRepository.class, + "revalidate", + DemoTenantEntitlementSnapshot.class); + assertWritableMandatory( + AccountTenantAuthorityEventRepository.class, "readCurrentByTenant", UUID.class); + } + @Test void appendBindsBillingEventIdAsUuidAndAuthorityEventIdAsVarcharText() { DSLContext dsl = mock(DSLContext.class); @@ -144,4 +161,15 @@ private static FreshTenantCreationEvidence freshTenantEvidence() { "NEW_GAME_ROW", evidenceDigest); } + + private static void assertWritableMandatory( + Class repositoryType, String methodName, Class... parameterTypes) + throws NoSuchMethodException { + Method method = repositoryType.getMethod(methodName, parameterTypes); + Transactional transaction = method.getAnnotation(Transactional.class); + + assertThat(transaction).isNotNull(); + assertThat(transaction.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transaction.readOnly()).isFalse(); + } } From 43c2a382c1da7080e8563a9ca52e0a9c29aca534 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:27:30 +1300 Subject: [PATCH 26/39] Fix Account entitlement replay and exact shared evidence binding --- .../player-access-and-session.md | 2 +- ...ountTenantEntitlementOutboxRepository.java | 2 +- ...EntitlementPersistenceIntegrationTest.java | 40 ++++ ...TenantEntitlementOutboxRepositoryTest.java | 179 ++++++++++++++++++ ...GameDesignPublicationTerminalEvidence.java | 12 ++ .../AuthoredDraftPublishSelectionBinding.java | 2 +- ...ublishedRealmEntryPolicyReadGrpcCodec.java | 42 +++- .../tenant/AuthoredWorldSourceDigest.java | 25 ++- .../tenant/RuntimeTenantIdentityEvidence.java | 32 +--- .../WorldPublishedStartLocationEvidence.java | 6 +- .../AuthoredWorldSourceEvidenceTest.java | 30 ++- .../RuntimeTenantIdentityEvidenceTest.java | 19 ++ ...shedRealmEntryPolicyReadGrpcCodecTest.java | 73 +++++++ ...lishedRealmEntryPolicySetEvidenceTest.java | 76 ++++++++ ...ldPublishedStartLocationGrpcCodecTest.java | 56 ++++++ .../authoring/DraftCommitBindingTest.java | 21 ++ 16 files changed, 562 insertions(+), 55 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5304edf7eb..c7955e1553 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. -Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Consolidated validation passed 593 Account unit cases, five shared World hold cases, jOOQ generation, and integration-test compilation. Current PostgreSQL-backed integration sources, including the new later-generation JOIN case, compiled but were unrun locally. An earlier hosted Account run executed 74 integration cases and found four fixture failures; their corrections are present, but this current head still requires exact-head hosted proof. +Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java index a5f7971da6..d68b523462 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -62,7 +62,7 @@ public Event append(UUID tenantId, UUID requestId, LongFunction eventFact long currentSequence = nonnegative(stream, "last_sequence"); Record priorRequest = dsl.fetchOne( - "SELECT tenant_billing_sequence, event_id, event_digest, payload " + "SELECT tenant_billing_sequence, request_id, event_id, event_digest, payload " + "FROM account_tenant_entitlement_outbox_events " + "WHERE tenant_uuid = ? AND request_id = ?", tenantId, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index 2ab572c80b..5dd0eca12d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -7,6 +7,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -160,6 +161,45 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc true); DemoTenantEntitlementSnapshot first = inTransaction(context.transaction(), () -> entitlements.provision(create, source)); + var exactEvent = + DemoTenantEntitlementEventV1Codec.seal( + create, + source, + first.entitlementVersion(), + first.tenantAuthorityGeneration(), + first.tenantAuthoritySourceVersion(), + first.tenantBillingSequence()); + var repeatedAppend = + inTransaction( + context.transaction(), + () -> + java.util.List.of( + outboxRepository.append(tenantId, create.requestId(), ignored -> exactEvent), + outboxRepository.append(tenantId, create.requestId(), ignored -> exactEvent))); + assertThat(repeatedAppend).hasSize(2); + for (var replay : repeatedAppend) { + assertThat(replay.requestId()).isEqualTo(exactEvent.requestId()); + assertThat(replay.eventId()).isEqualTo(exactEvent.eventId()); + assertThat(replay.eventDigest()).isEqualTo(exactEvent.eventDigest()); + assertThat(replay.tenantBillingSequence()).isEqualTo(exactEvent.tenantBillingSequence()); + assertThat(replay.payload()).containsExactly(exactEvent.payload()); + } + assertThat( + context + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams WHERE tenant_uuid = ?", + tenantId) + .get("last_sequence", Long.class)) + .isEqualTo(1L); + assertThat( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) AS event_count FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId) + .get("event_count", Long.class)) + .isEqualTo(1L); assertThat(first.canonicalTenantId()).isEqualTo(tenantId); assertThat(first.sourceEvidence()).isEqualTo(source); assertThat(first.entitlementKind()).isEqualTo("NON_PAID_DEMO"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java new file mode 100644 index 0000000000..f73645b728 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java @@ -0,0 +1,179 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantEntitlementOutboxRepositoryTest { + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String SOURCE_REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactReplayReadsRequestIdFromTheSelectedJooqProjectionWithoutMutation() { + DSLContext dsl = mock(DSLContext.class); + Event committed = event(true); + doReturn(streamProjection(1L)) + .doReturn(eventProjection(committed)) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + AccountTenantEntitlementOutboxRepository repository = + new AccountTenantEntitlementOutboxRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + AtomicInteger factoryCalls = new AtomicInteger(); + + Event replay = + repository.append( + TENANT_ID, + REQUEST_ID, + sequence -> { + factoryCalls.incrementAndGet(); + assertThat(sequence).isEqualTo(1L); + return committed; + }); + + assertThat(replay.requestId()).isEqualTo(committed.requestId()); + assertThat(replay.eventId()).isEqualTo(committed.eventId()); + assertThat(replay.eventDigest()).isEqualTo(committed.eventDigest()); + assertThat(replay.payload()).containsExactly(committed.payload()); + assertThat(factoryCalls).hasValue(1); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl, times(2)).fetchOne(sql.capture(), any(Object[].class)); + assertThat(sql.getAllValues().get(1)).contains("request_id"); + verify(dsl, never()) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("UPDATE "), any(Object[].class)); + verify(dsl, never()) + .execute( + org.mockito.ArgumentMatchers.startsWith( + "INSERT INTO account_tenant_entitlement_outbox_events"), + any(Object[].class)); + } + + @Test + void exactRequestReplayWithChangedPayloadRemainsAnIdempotencyConflict() { + DSLContext dsl = mock(DSLContext.class); + Event committed = event(true); + doReturn(streamProjection(1L)) + .doReturn(eventProjection(committed)) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + AccountTenantEntitlementOutboxRepository repository = + new AccountTenantEntitlementOutboxRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.append(TENANT_ID, REQUEST_ID, sequence -> event(false))) + .isInstanceOfSatisfying( + DemoTenantEntitlementException.class, + exception -> + assertThat(exception.code()) + .isEqualTo(DemoTenantEntitlementException.Code.IDEMPOTENCY_CONFLICT)); + verify(dsl, never()) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("UPDATE "), any(Object[].class)); + verify(dsl, never()) + .execute( + org.mockito.ArgumentMatchers.startsWith( + "INSERT INTO account_tenant_entitlement_outbox_events"), + any(Object[].class)); + } + + private static Event event(boolean gameplayAvailable) { + FreshTenantCreationEvidence source = sourceEvidence(); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + SOURCE_REQUEST_ID, + SOURCE_REQUEST_DIGEST, + null, + null, + null, + gameplayAvailable, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + return DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + } + + private static FreshTenantCreationEvidence sourceEvidence() { + String namespace = "prod"; + String sourceTenantKey = "tenant-source-44444444"; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + namespace, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + namespace, + SOURCE_REQUEST_ID, + SOURCE_OPERATION_ID, + SOURCE_REQUEST_DIGEST, + TENANT_ID, + 7001L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static Record streamProjection(long sequence) { + var field = DSL.field("last_sequence", Long.class); + Record projection = DSL.using(SQLDialect.POSTGRES).newRecord(field); + projection.set(field, sequence); + return projection; + } + + private static Record eventProjection(Event event) { + var sequence = DSL.field("tenant_billing_sequence", Long.class); + var requestId = DSL.field("request_id", UUID.class); + var eventId = DSL.field("event_id", UUID.class); + var digest = DSL.field("event_digest", String.class); + var payload = DSL.field("payload", byte[].class); + Record projection = + DSL.using(SQLDialect.POSTGRES).newRecord(sequence, requestId, eventId, digest, payload); + projection.set(sequence, event.tenantBillingSequence()); + projection.set(requestId, event.requestId()); + projection.set(eventId, event.eventId()); + projection.set(digest, event.eventDigest()); + projection.set(payload, event.payload()); + return projection; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index f83405fcb5..88c9c8ff89 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -352,6 +352,18 @@ public static GameDesignPublicationTerminalEvidence fromStored(byte[] bytes) { return result; } + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof GameDesignPublicationTerminalEvidence evidence + && Arrays.equals(canonicalBytes(), evidence.canonicalBytes())); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + private static void uuid(UUID id) { if (id == null || id.equals(new UUID(0L, 0L))) throw new IllegalArgumentException("Non-nil UUID required"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java index 9c1d742629..2095d951fa 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java @@ -142,7 +142,7 @@ public static AuthoredDraftPublishSelectionBinding fromStored( } return selection; } catch (RuntimeException exception) { - throw new IllegalStateException("Stored authored Draft selection is corrupt", exception); + throw new IllegalArgumentException("Stored authored Draft selection is corrupt", exception); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java index 0b34e8d1eb..5d05f0b6cb 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java @@ -118,7 +118,11 @@ public static PublishedRealmEntryPolicySetEvidence fromResponse( PublishedRealmEntryPolicySetEvidence complete = PublishedRealmEntryPolicySetEvidence.fromStored( response.getPolicySetEvidence().toByteArray()); - requireTarget(request.canonicalTenantId(), request.canonicalVersionId(), complete); + requireTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + complete); requireSelector(complete, request.worldSlug(), request.realmSlug()); return complete; } @@ -148,37 +152,57 @@ public static PublishedRealmEntryPolicySetEvidence fromResponse( PublishedRealmEntryPolicySetEvidence complete = PublishedRealmEntryPolicySetEvidence.fromStored( response.getPolicySetEvidence().toByteArray()); - requireTarget(request.canonicalTenantId(), request.canonicalVersionId(), complete); + requireTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + complete); return complete; } private static PublishedRealmEntryPolicySetEvidence verifiedFor( ResolveRequest request, PublishedRealmEntryPolicySetEvidence evidence) { Objects.requireNonNull(request, "request"); - return verifiedFor(request.canonicalTenantId(), request.canonicalVersionId(), evidence); + return verifiedFor( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + evidence); } private static PublishedRealmEntryPolicySetEvidence verifiedFor( ListRequest request, PublishedRealmEntryPolicySetEvidence evidence) { Objects.requireNonNull(request, "request"); - return verifiedFor(request.canonicalTenantId(), request.canonicalVersionId(), evidence); + return verifiedFor( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + evidence); } private static PublishedRealmEntryPolicySetEvidence verifiedFor( - UUID tenantId, UUID versionId, PublishedRealmEntryPolicySetEvidence evidence) { + String targetNamespace, + UUID tenantId, + UUID versionId, + PublishedRealmEntryPolicySetEvidence evidence) { Objects.requireNonNull(evidence, "evidence"); PublishedRealmEntryPolicySetEvidence complete = PublishedRealmEntryPolicySetEvidence.fromStored(evidence.canonicalBytes()); - requireTarget(tenantId, versionId, complete); + requireTarget(targetNamespace, tenantId, versionId, complete); return complete; } private static void requireTarget( - UUID tenantId, UUID versionId, PublishedRealmEntryPolicySetEvidence evidence) { - if (!evidence.target().canonicalTenantId().equals(tenantId) + String targetNamespace, + UUID tenantId, + UUID versionId, + PublishedRealmEntryPolicySetEvidence evidence) { + var operation = GameDesignPublicationOperationBinding.fromStored(evidence.operationBytes()); + if (!operation.world().request().targetNamespace().equals(targetNamespace) + || !evidence.target().canonicalTenantId().equals(tenantId) || !evidence.target().canonicalVersionId().equals(versionId)) { throw new IllegalArgumentException( - "Published policy evidence changed the exact owner target"); + "Published policy evidence changed the exact owner target namespace or identity"); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java index a6a4a31297..18ea92cef5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java @@ -61,13 +61,7 @@ public static String evidenceDigest( if (!GameTenantCreationDigest.isDigest(requestDigest)) { throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); } - if (sourceGameRowId <= 0) { - throw new IllegalArgumentException("sourceGameRowId must be positive"); - } - validateSourceGameTenantKey(sourceGameTenantKey); - if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { - throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); - } + validateSourceGameIdentity(sourceGameRowId, sourceGameTenantKey, provenanceKind); return GameTenantCreationDigest.digest( RECEIPT_DOMAIN, targetNamespace, @@ -130,6 +124,15 @@ private static void validateDisplayName(String value) { GameTenantCreationDigest.utf8ByteLength(value); } + static void validateSourceGameIdentity( + long sourceGameRowId, String sourceGameTenantKey, String provenanceKind) { + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + validateSourceGameTenantKey(sourceGameTenantKey); + validateProvenanceKind(provenanceKind); + } + private static void validateSourceGameTenantKey(String value) { Objects.requireNonNull(value, "sourceGameTenantKey"); if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { @@ -138,7 +141,13 @@ private static void validateSourceGameTenantKey(String value) { GameTenantCreationDigest.utf8ByteLength(value); } - private static void requireNonNil(UUID value, String label) { + private static void validateProvenanceKind(String value) { + if (!"NEW_GAME_ROW".equals(value) && !"RETAINED_GAME_V29".equals(value)) { + throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); + } + } + + static void requireNonNil(UUID value, String label) { Objects.requireNonNull(value, label); if (NIL_UUID.equals(value)) { throw new IllegalArgumentException(label + " must not be nil"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java index 06366df88b..01a522315e 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidence.java @@ -1,7 +1,5 @@ package net.firedevops.firemud.common.tenant; -import java.nio.charset.StandardCharsets; -import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -15,9 +13,6 @@ public record RuntimeTenantIdentityEvidence( String sourceGameTenantKey, String provenanceKind) { private static final int SCHEMA_VERSION = 1; - private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final int MAX_SOURCE_KEY_CODE_POINTS = 36; - private static final int MAX_SOURCE_KEY_UTF16_LENGTH = 72; public RuntimeTenantIdentityEvidence { if (schemaVersion != SCHEMA_VERSION) { @@ -26,28 +21,9 @@ public record RuntimeTenantIdentityEvidence( if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); } - requireNonNil(requestId, "requestId"); - requireNonNil(canonicalTenantId, "canonicalTenantId"); - if (sourceGameRowId <= 0) { - throw new IllegalArgumentException("sourceGameRowId must be positive"); - } - Objects.requireNonNull(sourceGameTenantKey, "sourceGameTenantKey"); - if (sourceGameTenantKey.isBlank() - || sourceGameTenantKey.length() > MAX_SOURCE_KEY_UTF16_LENGTH - || sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) - > MAX_SOURCE_KEY_CODE_POINTS - || !StandardCharsets.UTF_8.newEncoder().canEncode(sourceGameTenantKey)) { - throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); - } - if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { - throw new IllegalArgumentException("Runtime tenant provenance kind is not recognized"); - } - } - - private static void requireNonNil(UUID value, String label) { - Objects.requireNonNull(value, label); - if (NIL_UUID.equals(value)) { - throw new IllegalArgumentException(label + " must not be nil"); - } + AuthoredWorldSourceDigest.requireNonNil(requestId, "requestId"); + AuthoredWorldSourceDigest.requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateSourceGameIdentity( + sourceGameRowId, sourceGameTenantKey, provenanceKind); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java index 2db322fe14..37993f8dc3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -539,11 +539,7 @@ public record OwnedAffectedTuple( if (scopeType.isEmpty() != scopeId.isEmpty()) { throw new IllegalArgumentException("scopeType and scopeId must both be present or absent"); } - if (expectedEpoch == null - || !expectedEpoch.matches("0|[1-9][0-9]*") - || new java.math.BigInteger(expectedEpoch) - .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) - > 0) { + if (expectedEpoch == null || !expectedEpoch.matches("0|[1-9][0-9]*")) { throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java index 523aafbebe..7f2b8cbb06 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java @@ -71,6 +71,27 @@ void acceptsMaximumSelectorBytesAndDisplayCodePoints() { .hasSize(100); } + @Test + void acceptsSourceTenantKeyAtThirtySixCodePointsAndSeventyTwoUtf16Units() { + String maximumSourceKey = "😀".repeat(36); + AuthoredWorldSourceEvidence evidence = evidence(maximumSourceKey, PROVENANCE); + + assertThat(evidence.sourceGameTenantKey()).hasSize(72); + assertThat(evidence.sourceGameTenantKey().codePointCount(0, 72)).isEqualTo(36); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "😀".repeat(37), + PROVENANCE); + } + @Test void rejectsUnsupportedVersionMalformedIdentitySelectorsAndDisplayName() { AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); @@ -311,6 +332,11 @@ void rejectsChangedRequestReceiptSourceBoundsAndUnknownProvenance() { } private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { + return evidence(SOURCE_GAME_TENANT_KEY, provenanceKind); + } + + private static AuthoredWorldSourceEvidence evidence( + String sourceGameTenantKey, String provenanceKind) { String requestDigest = AuthoredWorldSourceDigest.requestDigest( NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME); @@ -325,7 +351,7 @@ private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { WORLD_SLUG, DISPLAY_NAME, SOURCE_GAME_ROW_ID, - SOURCE_GAME_TENANT_KEY, + sourceGameTenantKey, provenanceKind); return new AuthoredWorldSourceEvidence( 1, @@ -338,7 +364,7 @@ private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { WORLD_SLUG, DISPLAY_NAME, SOURCE_GAME_ROW_ID, - SOURCE_GAME_TENANT_KEY, + sourceGameTenantKey, provenanceKind, evidenceDigest); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java index 0be76125d2..67a888ac51 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java @@ -16,6 +16,25 @@ void acceptsNewAndRetainedOwnerEvidence() { assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); } + @Test + void acceptsTheSharedSourceTenantKeyCodePointAndUtf16Boundary() { + String maximumSourceKey = "😀".repeat(36); + var evidence = + new RuntimeTenantIdentityEvidence( + 1, "test", REQUEST_ID, TENANT_ID, 42L, maximumSourceKey, "NEW_GAME_ROW"); + + assertThat(evidence.sourceGameTenantKey()).hasSize(72); + assertThat(evidence.sourceGameTenantKey().codePointCount(0, 72)).isEqualTo(36); + assertInvalid( + 1, + evidence.targetNamespace(), + evidence.requestId(), + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + "😀".repeat(37), + evidence.provenanceKind()); + } + @Test void rejectsUnsupportedOrIncompleteOwnerEvidence() { RuntimeTenantIdentityEvidence valid = evidence("NEW_GAME_ROW"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java index 1da90617e0..cbd99d8356 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java @@ -206,6 +206,79 @@ void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { .build())); } + @Test + void bothReadShapesBindSealedNamespaceTenantAndVersion() throws Exception { + PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(false); + var originalList = listRequest(fixture, "99999999-9999-4999-8999-999999999999"); + var crossNamespaceList = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + "other", + originalList.readRequestId(), + originalList.canonicalTenantId(), + originalList.canonicalVersionId()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + crossNamespaceList, fixture.set())); + var substitutedList = + ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(crossNamespaceList)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + crossNamespaceList, substitutedList)); + + var crossTenantList = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + originalList.targetNamespace(), + originalList.readRequestId(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + originalList.canonicalVersionId()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossTenantList, fixture.set())); + var crossVersionList = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + originalList.targetNamespace(), + originalList.readRequestId(), + originalList.canonicalTenantId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossVersionList, fixture.set())); + + var originalResolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); + var crossNamespaceResolve = + new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + "other", + originalResolve.readRequestId(), + originalResolve.canonicalTenantId(), + originalResolve.canonicalVersionId(), + originalResolve.worldSlug(), + originalResolve.realmSlug()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + crossNamespaceResolve, fixture.set())); + var substitutedResolve = + ResolvePublishedRealmEntryPolicyResponse.newBuilder() + .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(crossNamespaceResolve)) + .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) + .build(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + crossNamespaceResolve, substitutedResolve)); + } + @Test void completeCarrierRejectsCountOrderAndDigestSubstitutionAtTheWireBoundary() throws Exception { PublishedRealmEntryPolicySetEvidenceTest.Fixture fixture = fixture(true); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index 547ca56002..d08243625a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -11,6 +12,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -20,6 +22,8 @@ import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -64,6 +68,78 @@ void terminalReadRequestUsesCanonicalByteValueEquality() throws Exception { assertThat(changedIdentity).isNotEqualTo(expected); } + @Test + void terminalEvidenceAndPublishedOrNoPublicationReadResultsUseCanonicalByteValueEquality() + throws Exception { + var fixture = fixture(false); + var terminal = fixture.terminal(); + var decodedTerminal = + GameDesignPublicationTerminalEvidence.fromStored(terminal.canonicalBytes()); + assertThat(decodedTerminal).isEqualTo(terminal); + assertThat(decodedTerminal.hashCode()).isEqualTo(terminal.hashCode()); + + var request = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + fixture.operation().world().request().targetNamespace(), + uuid("10101010-1010-4010-8010-101010101010"), + fixture.operation().canonicalBytes()); + var published = new ReadResult(request, Status.PUBLISHED, Optional.of(terminal)); + var decodedPublished = ReadResult.fromStored(published.canonicalBytes()); + assertThat(decodedPublished).isEqualTo(published); + assertThat(decodedPublished.hashCode()).isEqualTo(published.hashCode()); + + var noPublicationTerminal = + new GameDesignPublicationTerminalEvidence( + fixture.operation().canonicalBytes(), Outcome.NO_PUBLICATION, null, null); + var noPublication = + new ReadResult(request, Status.NO_PUBLICATION, Optional.of(noPublicationTerminal)); + var decodedNoPublication = ReadResult.fromStored(noPublication.canonicalBytes()); + assertThat(decodedNoPublication).isEqualTo(noPublication); + assertThat(decodedNoPublication.hashCode()).isEqualTo(noPublication.hashCode()); + + var changedTerminal = + terminal( + fixture.operation(), + fixture.release("changed-generation"), + terminal.publicationVersionStateEpoch()); + assertThat(changedTerminal).isNotEqualTo(terminal); + assertThat(new ReadResult(request, Status.PUBLISHED, Optional.of(changedTerminal))) + .isNotEqualTo(published); + } + + @Test + void storedDraftSelectionRetainsCanonicalValidationAndTheNestedWireFailureCause() + throws Exception { + var selection = fixture(false).operation().account().input().selection(); + + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson() + " ", selection.digest())) + .isInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not exact canonical JSON"); + }); + + ObjectNode corrupted = (ObjectNode) JSON.readTree(selection.canonicalJson()); + corrupted.put("selectedCommitBindingJson", "{}"); + String corruptedJson = JSON.writeValueAsString(corrupted); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored(corruptedJson, selection.digest())) + .isInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + }); + } + @Test void completeSetRetainsTheActualOperationCaptureTerminalAndOrderedSourceRows() throws Exception { Fixture fixture = fixture(false); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java index 58a6606492..e39fab893d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -16,6 +16,7 @@ import org.junit.jupiter.api.Test; class WorldPublishedStartLocationGrpcCodecTest { + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; private static final tools.jackson.databind.ObjectMapper JSON = new tools.jackson.databind.ObjectMapper(); @@ -122,6 +123,46 @@ void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws .hasMessageContaining("intake request"); } + @Test + void requestCarrierAcceptsUnboundedDraftEpochAndRejectsMalformedCounters() throws Exception { + WorldPublishedStartLocationEvidence.Request base = evidence().request(); + var tuple = base.worldAffectedTuples().getFirst(); + var largeEpochTuple = + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + LARGE_EPOCH); + var carrierRequest = + new WorldPublishedStartLocationEvidence.Request( + base.targetNamespace(), + base.canonicalTenantId(), + base.canonicalVersionId(), + base.intakeRequestId(), + base.publicationFence(), + base.publicationRequestId(), + base.requestDigest(), + base.versionStateEpoch(), + base.publishWorkflowId(), + base.appliedCommitId(), + base.contentDigest(), + base.digestSchemaVersion(), + List.of(largeEpochTuple)); + var roundTrip = + WorldPublishedStartLocationGrpcCodec.fromRequest( + WorldPublishedStartLocationGrpcCodec.toRequest(carrierRequest)); + + assertThat(roundTrip).isEqualTo(carrierRequest); + assertThat(roundTrip.worldAffectedTuples().getFirst().expectedEpoch()).isEqualTo(LARGE_EPOCH); + + assertInvalidExpectedEpoch(tuple, null); + assertInvalidExpectedEpoch(tuple, "-1"); + assertInvalidExpectedEpoch(tuple, "01"); + assertInvalidExpectedEpoch(tuple, "not-a-decimal"); + } + static WorldPublishedStartLocationEvidence evidence() throws Exception { WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); OwnerReadback committed = freshGraphReadback(terminalRequest); @@ -176,4 +217,19 @@ private static OwnerReadback freshGraphReadback(WorldDraftTerminalReadEvidence.R private static UUID uuid(String value) { return UUID.fromString(value); } + + private static void assertInvalidExpectedEpoch( + WorldPublishedStartLocationEvidence.OwnedAffectedTuple template, String expectedEpoch) { + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + template.owner(), + template.aggregateType(), + template.aggregateId(), + template.scopeType(), + template.scopeId(), + expectedEpoch)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-negative decimal"); + } } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java index de3e7b5d75..7e02ff59a5 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; @@ -177,6 +178,26 @@ void rejectsNonCanonicalCountersAndNilOrUnprovedTargetIdentity() { .hasMessageContaining("must match exactly"); } + @Test + void worldStartLocationTupleCarriesTheSameUnboundedCanonicalDraftEpoch() { + AffectedUnit draftUnit = + binding().affectedUnits().stream() + .filter(unit -> unit.owner() == Owner.WORLD_MANAGEMENT) + .findFirst() + .orElseThrow(); + OwnedAffectedTuple worldTuple = + new OwnedAffectedTuple( + draftUnit.owner().name(), + draftUnit.aggregateType(), + draftUnit.aggregateId(), + draftUnit.scopeType(), + draftUnit.scopeId(), + draftUnit.expectedEpoch()); + + assertThat(draftUnit.expectedEpoch()).isEqualTo(LARGE_EPOCH); + assertThat(worldTuple.expectedEpoch()).isEqualTo(draftUnit.expectedEpoch()); + } + private DraftCommitBinding binding() { return DraftCommitBinding.create( new TargetProof( From 5128ad7d1923139325b23c5049cc86b30f177e37 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:44:16 +1300 Subject: [PATCH 27/39] Make entitlement replay integration row assertions explicitly non-null --- ...EntitlementPersistenceIntegrationTest.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index 5dd0eca12d..d81f9bf6e0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -185,19 +185,23 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc assertThat(replay.payload()).containsExactly(exactEvent.payload()); } assertThat( - context - .dsl() - .fetchOne( - "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams WHERE tenant_uuid = ?", - tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams WHERE tenant_uuid = ?", + tenantId), + "expected entitlement outbox stream row") .get("last_sequence", Long.class)) .isEqualTo(1L); assertThat( - context - .dsl() - .fetchOne( - "SELECT COUNT(*) AS event_count FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", - tenantId) + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) AS event_count FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + tenantId), + "expected entitlement outbox event count row") .get("event_count", Long.class)) .isEqualTo(1L); assertThat(first.canonicalTenantId()).isEqualTo(tenantId); From f59c45b7439fc61acfe8c12bccaa1ae05b2136cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:54:17 +1300 Subject: [PATCH 28/39] Bind roster policy evidence to its exact workload namespace --- ...onicalGameplayRosterOwnerReadEvidence.java | 8 +- ...alGameplayRosterOwnerReadEvidenceTest.java | 79 ++++++++++++++++++- 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java index 86a1e642c9..905932f518 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java @@ -5,6 +5,7 @@ import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; @@ -80,9 +81,12 @@ private static void requireProofMatches( private static void requirePolicyMatches( Request request, PublishedRealmEntryPolicySetEvidence evidence) { - if (!evidence.target().canonicalTenantId().equals(request.canonicalTenantUuid()) + var operation = GameDesignPublicationOperationBinding.fromStored(evidence.operationBytes()); + if (!operation.world().request().targetNamespace().equals(request.targetNamespace()) + || !evidence.target().canonicalTenantId().equals(request.canonicalTenantUuid()) || !evidence.target().canonicalVersionId().equals(request.canonicalVersionUuid())) { - throw new IllegalArgumentException("Game Design policy set changed the exact tenant/version"); + throw new IllegalArgumentException( + "Game Design policy set changed the exact owner target namespace or tenant/version"); } List matches = evidence.policies().stream() diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java index 32ae8a3292..46bd45a5e0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java @@ -7,6 +7,7 @@ import com.google.protobuf.UnknownFieldSet; import java.time.Instant; import java.util.UUID; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; import org.junit.jupiter.api.Test; @@ -31,6 +32,74 @@ void acceptsExactCommittedWorldHoldAndCompletePreseededPolicySet() throws Except net.firedevops.firemud.common.publication.RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); } + @Test + void rejectsExactPolicySetSealedForAnotherWorkloadNamespace() throws Exception { + var evidence = fixture(); + var policyOperation = + GameDesignPublicationOperationBinding.fromStored( + evidence.publishedPolicySetEvidence().operationBytes()); + var hold = evidence.gameSessionOwnerProof().holdIdentity(); + var priorHoldRequest = hold.request(); + var wrongNamespaceHoldRequest = + new WorldCanonicalInitialAdmissionHold.Request( + TARGET_NAMESPACE, + priorHoldRequest.canonicalTenantId(), + priorHoldRequest.worldSlug(), + priorHoldRequest.realmId(), + priorHoldRequest.playableStateNamespaceId(), + priorHoldRequest.playableStateScope(), + priorHoldRequest.canonicalGameInstanceId(), + priorHoldRequest.canonicalVersionId(), + priorHoldRequest.activeLifecycleEpoch(), + priorHoldRequest.initialAdmissionRequestId(), + priorHoldRequest.initialAdmissionRequestDigest(), + priorHoldRequest.initialAdmissionOrigin(), + priorHoldRequest.expectedCatalogRevision(), + priorHoldRequest.expectedPriorPointerVersion()); + var wrongNamespaceHold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + wrongNamespaceHoldRequest, hold.holdId(), hold.holdFence()); + var originalProof = evidence.gameSessionOwnerProof(); + var wrongNamespaceProof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + wrongNamespaceHold, + originalProof.outcome(), + originalProof.committedPointerVersion(), + originalProof.auditEventId(), + originalProof.proofDigest(), + originalProof.positiveDurableAbort(), + originalProof.terminalAt()); + var originalRequest = evidence.request(); + var wrongNamespaceRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + originalRequest.requestUuid(), + originalRequest.canonicalAccountUuid(), + TARGET_NAMESPACE, + originalRequest.canonicalTenantUuid(), + originalRequest.worldSlug(), + originalRequest.realmUuid(), + originalRequest.realmSlug(), + originalRequest.playableStateNamespaceUuid(), + originalRequest.playableStateScope(), + originalRequest.canonicalGameInstanceUuid(), + originalRequest.canonicalVersionUuid(), + originalRequest.expectedCatalogRevision(), + originalRequest.expectedPointerVersion(), + originalRequest.expectedActiveWorldEpoch()); + assertThat(policyOperation.world().request().targetNamespace()) + .isNotEqualTo(wrongNamespaceRequest.targetNamespace()); + + assertThatThrownBy( + () -> + new CanonicalGameplayRosterOwnerReadEvidence( + wrongNamespaceRequest, + evidence.admissionPointerSnapshotDigest(), + wrongNamespaceProof, + evidence.publishedPolicySetEvidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target namespace"); + } + @Test void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception { var good = fixture(); @@ -45,7 +114,7 @@ void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception new CanonicalGameplayRosterOwnerReadEvidence.Request( good.request().requestUuid(), ACCOUNT, - TARGET_NAMESPACE, + good.request().targetNamespace(), good.request().canonicalTenantUuid(), "earth", REALM, @@ -70,7 +139,7 @@ void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception new CanonicalGameplayRosterOwnerReadEvidence.Request( good.request().requestUuid(), ACCOUNT, - TARGET_NAMESPACE, + good.request().targetNamespace(), good.request().canonicalTenantUuid(), "earth", REALM, @@ -216,11 +285,13 @@ void grpcCodecRoundTripsCompleteProofAndRejectsUnknownPartialOrChangedEcho() thr private static CanonicalGameplayRosterOwnerReadEvidence fixture() throws Exception { var set = PublishedRealmEntryPolicySetEvidenceTest.preseededSetFixture(); + var operation = GameDesignPublicationOperationBinding.fromStored(set.operationBytes()); + String targetNamespace = operation.world().request().targetNamespace(); UUID tenant = set.target().canonicalTenantId(); UUID version = set.target().canonicalVersionId(); var holdRequest = new WorldCanonicalInitialAdmissionHold.Request( - TARGET_NAMESPACE, + targetNamespace, tenant, "earth", REALM, @@ -252,7 +323,7 @@ private static CanonicalGameplayRosterOwnerReadEvidence fixture() throws Excepti new CanonicalGameplayRosterOwnerReadEvidence.Request( uuid("11111111-1111-4111-8111-111111111111"), ACCOUNT, - TARGET_NAMESPACE, + targetNamespace, tenant, "earth", REALM, From 269dc1fd60a062a6fd1b03d44a42201ad7045fdd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:23:05 +1300 Subject: [PATCH 29/39] Reject oversized publication evidence and align exact owner-read proof --- .../v1/draft_terminal_service.proto | 4 +- ...GameDesignPublicationTerminalEvidence.java | 6 +- .../WorldPublishedStartLocationEvidence.java | 6 +- ...nPublicationTerminalEvidenceCodecTest.java | 81 +++++++++++++++++++ ...dActorAssignmentOwnerReadEvidenceTest.java | 2 +- 5 files changed, 91 insertions(+), 8 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java diff --git a/protos/world-management/v1/draft_terminal_service.proto b/protos/world-management/v1/draft_terminal_service.proto index b839e55728..4e33933b9e 100644 --- a/protos/world-management/v1/draft_terminal_service.proto +++ b/protos/world-management/v1/draft_terminal_service.proto @@ -33,6 +33,8 @@ message ReadWorldDraftTerminalOutcomeResponse { string read_request_id = 3; bytes original_account_binding = 4; WorldDraftTerminalReadStatus status = 5; - // Canonical account-draft-owner-readback/v1 bytes. Empty only for UNKNOWN. + // Canonical account-draft-owner-readback/v1 or /v2 bytes; the version matches + // the original Account fence schema (fence v1 -> readback v1, v2 -> v2). + // Empty only for UNKNOWN. bytes owner_readback_bytes = 6; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index 88c9c8ff89..d99764dd3e 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -490,7 +490,11 @@ void expect(String value) { } int positiveInt() { - return Math.toIntExact(positiveLong(text())); + long value = positiveLong(text()); + if (value > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Positive integer exceeds supported range"); + } + return (int) value; } int count() { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java index 37993f8dc3..a84d164c0a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -21,7 +21,6 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; -import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import tools.jackson.core.StreamReadFeature; @@ -219,10 +218,7 @@ private static void requireRelation( account.inputDigest(), accountBytes, appliedBytes); - var terminalResponse = - WorldDraftTerminalReadGrpcCodec.toResponse( - terminalRequest, java.util.Optional.of(terminalReadback)); - WorldDraftTerminalReadGrpcCodec.fromResponse(terminalRequest, terminalResponse); + new WorldDraftTerminalReadEvidence(terminalRequest, java.util.Optional.of(terminalReadback)); JsonNode applied = readApplied(appliedBytes); if (!"APPLIED".equals(text(applied, "status"))) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java new file mode 100644 index 0000000000..3d4e08d870 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import org.junit.jupiter.api.Test; + +class GameDesignPublicationTerminalEvidenceCodecTest { + @Test + void publicationCounterAboveIntRangeIsRejectedAsInvalidTerminalReadEvidence() throws Exception { + var fixture = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); + var request = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + fixture.operation().world().request().targetNamespace(), + java.util.UUID.fromString("10101010-1010-4010-8010-101010101010"), + fixture.operation().canonicalBytes()); + var result = new ReadResult(request, Status.PUBLISHED, Optional.of(fixture.terminal())); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + + byte[] malformedRelease = + replaceSegment( + fixture.terminal().releaseContent().canonicalBytes(), + 4, + "2147483648".getBytes(StandardCharsets.UTF_8)); + byte[] malformedTerminal = + replaceFrame(fixture.terminal().canonicalBytes(), 3, malformedRelease); + byte[] malformedResponse = replaceFrame(result.canonicalBytes(), 3, malformedTerminal); + + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponse)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported range"); + } + + private static byte[] replaceFrame(byte[] framed, int targetIndex, byte[] replacement) { + var input = ByteBuffer.wrap(framed); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + DraftAuthorizationFenceBinding.frame(output, index == targetIndex ? replacement : value); + } + return output.toByteArray(); + } + + private static byte[] replaceSegment(byte[] encoded, int targetIndex, byte[] replacement) { + var input = ByteBuffer.wrap(encoded); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int lengthStart = input.position(); + while (input.get() != ':') {} + int lengthEnd = input.position() - 1; + int length = + Integer.parseInt( + new String(encoded, lengthStart, lengthEnd - lengthStart, StandardCharsets.US_ASCII)); + byte[] value = new byte[length]; + input.get(value); + byte[] selected = index == targetIndex ? replacement : value; + output.writeBytes(Integer.toString(selected.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(selected); + } + return output.toByteArray(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java index 596f5dc9ee..06df7a9fa0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test; class PreseededActorAssignmentOwnerReadEvidenceTest { - private static final String TARGET_NAMESPACE = "gameplay"; + private static final String TARGET_NAMESPACE = "test"; private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); private static final UUID REALM = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); private static final UUID PLAYABLE_NAMESPACE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); From 52fb85ae23e5c940adce5b2526e2f7b930a56848 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:34:33 +1300 Subject: [PATCH 30/39] docs: distinguish tenant authority and first-JOIN event producers --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index c7955e1553..796c7135e7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -47,7 +47,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountMembershipAuthorityEventProducer` emits the canonical tenant authority event with billing cutoff from fresh source coordinates, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | From c5152a65f7f31cd7201cd0f16d0ff72ce531c6ce Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:07:12 +1300 Subject: [PATCH 31/39] fix(ci): refresh restored module dependency metadata --- .github/workflows/ci.yml | 2 +- dev-tools/tests/ci-lightweight-scope-contract.sh | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 36cb3f06ef..5cf5d4fe10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -992,7 +992,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew :${{ matrix.module }}:check -PfullCheck + ./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" - name: 📦 Build Runtime JAR diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 6144e19a55..a6bd96b863 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -243,6 +243,18 @@ security = load_workflow(sys.argv[2]) preview = load_workflow(sys.argv[3]) zap = load_workflow(sys.argv[4]) +module_checks_step = find_step( + ci, "build-and-test", "Run Gradle Checks", "ci workflow" +) +require_equal( + module_checks_step, + ("run",), + "echo \"::group::Run Module Validation\"\n" + "./gradlew --refresh-dependencies :${{ matrix.module }}:check -PfullCheck\n" + "echo \"::endgroup::\"\n", + "ci workflow", +) + require_equal( ci, ("jobs", "changes", "permissions", "pull-requests"), From 61886795fcf24f446805a32d28552bf464d89c64 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:47:15 +1300 Subject: [PATCH 32/39] fix(common): expose validated World APPLIED intake identity --- .../WorldDraftTerminalReadEvidence.java | 14 +++++ .../WorldDraftTerminalReadGrpcCodec.java | 5 +- .../WorldPublishedStartLocationEvidence.java | 53 ++----------------- .../WorldDraftTerminalReadGrpcCodecTest.java | 15 ++++-- 4 files changed, 32 insertions(+), 55 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java index 21aac2639d..19d24a9de5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java @@ -31,6 +31,20 @@ public record WorldDraftTerminalReadEvidence( }); } + /** Returns the intake request identity from this validated committed World APPLIED result. */ + public UUID appliedIntakeRequestId() { + DraftAuthorizationFenceBinding.OwnerReadback readback = + ownerReadback.orElseThrow( + () -> + new IllegalStateException( + "World APPLIED intake request requires a committed terminal readback")); + if (readback.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + throw new IllegalStateException( + "World APPLIED intake request requires a committed terminal readback"); + } + return WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, readback); + } + /** The canonical original Account binding and a separate caller-owned fresh read identity. */ public record Request( int schemaVersion, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java index a826e79d17..ebe63173ee 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -241,7 +241,7 @@ private static void requireExactOwnerReadback( /** * Checks this World carrier only; mutation/source semantics remain at the authenticated owner. */ - static void requireCommittedResult( + static UUID requireCommittedResult( WorldDraftTerminalReadEvidence.Request request, DraftAuthorizationFenceBinding.OwnerReadback readback) { try { @@ -296,7 +296,7 @@ static void requireCommittedResult( operation.expect(account.versionId().toString()); UUID versionIdentityOperationId = operation.canonicalUuid(); operation.expect(Long.toString(draft.target().gameDesignVersionRowId())); - operation.canonicalUuid(); // Intake request + UUID intakeRequestId = operation.canonicalUuid(); operation.canonicalUuid(); // Intake operation operation.digest(); // Intake request digest operation.canonicalUuid(); // Source operation @@ -358,6 +358,7 @@ static void requireCommittedResult( "resultingEpoch", new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()); } + return intakeRequestId; } catch (java.io.IOException | NoSuchAlgorithmException | RuntimeException invalid) { throw new IllegalArgumentException( "World committed readback has an invalid or substituted canonical APPLIED result", diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java index a84d164c0a..73e7691e73 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.common.world; import java.io.IOException; -import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -42,8 +41,6 @@ public record WorldPublishedStartLocationEvidence( byte[] originalAccountBindingBytes, byte[] appliedResultBytes) { public static final String SCHEMA = "world-published-start-location-evidence/v1"; - private static final int APPLIED_INTAKE_REQUEST_ID_FRAME = 13; - private static final Set EVIDENCE_FIELDS = Set.of( "schema", @@ -218,17 +215,14 @@ private static void requireRelation( account.inputDigest(), accountBytes, appliedBytes); - new WorldDraftTerminalReadEvidence(terminalRequest, java.util.Optional.of(terminalReadback)); - - JsonNode applied = readApplied(appliedBytes); - if (!"APPLIED".equals(text(applied, "status"))) { - throw new IllegalArgumentException( - "Published World selector requires the original APPLIED result"); - } - if (!request.intakeRequestId().equals(appliedIntakeRequestId(applied))) { + WorldDraftTerminalReadEvidence terminalEvidence = + new WorldDraftTerminalReadEvidence( + terminalRequest, java.util.Optional.of(terminalReadback)); + if (!request.intakeRequestId().equals(terminalEvidence.appliedIntakeRequestId())) { throw new IllegalArgumentException( "Published World selection differs from the original APPLIED intake request"); } + JsonNode applied = readApplied(appliedBytes); byte[] resultReceipt = base64(applied, "startLocationReceiptBase64"); if (!Arrays.equals(receiptBytes, resultReceipt)) { throw new IllegalArgumentException( @@ -266,43 +260,6 @@ private static JsonNode readApplied(byte[] bytes) { } } - /** Reads the immutable intake identity from the exact operation frame already codec-validated. */ - private static UUID appliedIntakeRequestId(JsonNode applied) { - ByteBuffer operation = ByteBuffer.wrap(base64(applied, "operationBytesBase64")); - String intakeRequestId = null; - for (int frameIndex = 0; frameIndex <= APPLIED_INTAKE_REQUEST_ID_FRAME; frameIndex++) { - if (operation.remaining() < Integer.BYTES) { - throw new IllegalArgumentException("World APPLIED operation frame is truncated"); - } - int frameLength = operation.getInt(); - if (frameLength < 0 || frameLength > operation.remaining()) { - throw new IllegalArgumentException("World APPLIED operation frame has an invalid length"); - } - byte[] frame = new byte[frameLength]; - operation.get(frame); - if (frameIndex == 0 - && !"world-draft-terminal-operation/v1" - .equals(new String(frame, StandardCharsets.UTF_8))) { - throw new IllegalArgumentException("Unsupported World APPLIED operation frame schema"); - } - if (frameIndex == APPLIED_INTAKE_REQUEST_ID_FRAME) { - try { - intakeRequestId = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) - .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) - .decode(java.nio.ByteBuffer.wrap(frame)) - .toString(); - } catch (java.nio.charset.CharacterCodingException invalid) { - throw new IllegalArgumentException( - "World APPLIED intake request frame is invalid", invalid); - } - } - } - return parseUuid(intakeRequestId, "APPLIED intakeRequestId"); - } - private static String prefixedSha256(byte[] bytes) { try { return "sha256:" diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index 649e3bbf8c..7d442beefc 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -134,6 +134,9 @@ void unknownIsExplicitAndCarriesNoOwnerResult() { assertThat(evidence.request()).isEqualTo(request); assertThat(evidence.ownerReadback()).isEmpty(); + assertThatThrownBy(evidence::appliedIntakeRequestId) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed terminal readback"); assertThat(response.getStatus()) .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); assertThat(response.getOwnerReadbackBytes()).isEmpty(); @@ -158,6 +161,9 @@ void exactAbortMustBeWorldAndMustEchoEveryRequestFieldAndOriginalBinding() { var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); var decodedAbort = evidence.ownerReadback().orElseThrow(); + assertThatThrownBy(evidence::appliedIntakeRequestId) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed terminal readback"); assertThat(decodedAbort.canonicalBytes()).containsExactly(abort.canonicalBytes()); assertThat(decodedAbort.fullBinding()).containsExactly(request.originalAccountBinding()); assertThat(decodedAbort.result()).containsExactly(1, 2, 3); @@ -233,12 +239,11 @@ void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSub var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); assertThat(response.getStatus()) .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); - assertThat( - WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) - .ownerReadback() - .orElseThrow() - .canonicalBytes()) + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(evidence.ownerReadback().orElseThrow().canonicalBytes()) .containsExactly(committed.canonicalBytes()); + assertThat(evidence.appliedIntakeRequestId()) + .isEqualTo(uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); assertThatThrownBy( () -> WorldDraftTerminalReadGrpcCodec.fromResponse( From e6ccbee53b56c411f2d7332b071785ab7ceb408b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:56:47 +1300 Subject: [PATCH 33/39] Reject overflowing publication epochs and decode read operation once --- ...GameDesignPublicationTerminalEvidence.java | 6 +- ...DesignPublicationTerminalReadEvidence.java | 3 +- ...nPublicationTerminalEvidenceCodecTest.java | 59 +++++++++++++++++++ ...lishedRealmEntryPolicySetEvidenceTest.java | 4 +- 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index d99764dd3e..bd6e98647a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -273,8 +273,12 @@ public GameDesignPublicationTerminalEvidence( this.release = release == null ? null : ReleaseContent.fromStored(release.canonicalBytes()); this.epoch = publicationVersionStateEpoch; if (release != null) { + long frozenEpoch = operation.world().request().versionStateEpoch(); + if (frozenEpoch == Long.MAX_VALUE) { + throw new IllegalArgumentException("Published version-state epoch exceeds owner range"); + } if (epoch <= 0 - || epoch != Math.addExact(operation.world().request().versionStateEpoch(), 1L) + || epoch != frozenEpoch + 1L || !Arrays.equals( release.worldStartLocationEvidence().canonicalBytes(), operation.world().canonicalBytes())) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java index 2d87c8a951..b4c088391f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java @@ -34,9 +34,8 @@ public record ReadRequest( throw new IllegalArgumentException( "Closed schema-1 namespace and non-nil read UUID required"); } - operationBytes = - GameDesignPublicationOperationBinding.fromStored(operationBytes).canonicalBytes(); var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + operationBytes = operation.canonicalBytes(); if (!targetNamespace.equals(operation.world().request().targetNamespace())) { throw new IllegalArgumentException("Read namespace differs from original World operation"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java index 3d4e08d870..6763a55fbe 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java @@ -1,5 +1,6 @@ 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.ByteString; @@ -8,13 +9,71 @@ import java.nio.charset.StandardCharsets; import java.util.Optional; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import org.junit.jupiter.api.Test; class GameDesignPublicationTerminalEvidenceCodecTest { + @Test + void maximumFrozenEpochIsRejectedAsInvalidEvidenceAndOrdinaryEpochRoundTrips() throws Exception { + var ordinary = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); + var ordinaryRequest = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + ordinary.operation().world().request().targetNamespace(), + java.util.UUID.fromString("10101010-1010-4010-8010-101010101010"), + ordinary.operation().canonicalBytes()); + var ordinaryResult = + new ReadResult(ordinaryRequest, Status.PUBLISHED, Optional.of(ordinary.terminal())); + var ordinaryResponse = + GameDesignPublicationTerminalReadGrpcCodec.toResponse(ordinaryRequest, ordinaryResult); + + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + ordinaryRequest, ordinaryResponse)) + .isEqualTo(ordinaryResult); + + GameDesignPublicationOperationBinding maxEpochOperation = + PublishedRealmEntryPolicySetEvidenceTest.operation(Long.MAX_VALUE); + var maxEpochRelease = + PublishedRealmEntryPolicySetEvidenceTest.release(maxEpochOperation, "generation-max"); + var malformedTerminal = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + malformedTerminal, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(malformedTerminal, maxEpochOperation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedTerminal, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(malformedTerminal, maxEpochRelease.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedTerminal, "1"); + + var malformedResponseBytes = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, ReadResult.SCHEMA); + var maxEpochRequest = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + maxEpochOperation.world().request().targetNamespace(), + java.util.UUID.fromString("20202020-2020-4020-8020-202020202020"), + maxEpochOperation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, maxEpochRequest.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(malformedResponseBytes, malformedTerminal.toByteArray()); + + var malformedWireResponse = + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponseBytes.toByteArray())) + .build(); + + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + maxEpochRequest, malformedWireResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Published version-state epoch exceeds owner range"); + } + @Test void publicationCounterAboveIntRangeIsRejectedAsInvalidTerminalReadEvidence() throws Exception { var fixture = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index d08243625a..a0bf6a573c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -594,7 +594,7 @@ private static GameDesignPublicationTerminalEvidence terminal( operation.canonicalBytes(), Outcome.PUBLISHED, release, epoch); } - private static ReleaseContent release( + static ReleaseContent release( GameDesignPublicationOperationBinding operation, String generation) { var request = operation.world().request(); var participants = @@ -638,7 +638,7 @@ private static ReleaseContent release( operation.world()); } - private static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { + static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var draft = From 6956f3ac2a85b0906d27e8a92521ab139991dca7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:07:36 +1300 Subject: [PATCH 34/39] Strengthen owner-evidence rejection and Account proof assertions --- ...countDemoTenantEntitlementPersistenceIntegrationTest.java | 4 +++- .../firemud/accountservice/AccountUuidTextTest.java | 3 ++- .../service/impl/RuntimeAccountIdentityGrpcServiceTest.java | 3 ++- .../world/CanonicalGameplayRosterOwnerReadEvidenceTest.java | 5 ++++- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index d81f9bf6e0..3a6e0148c3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -374,7 +374,9 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc tenantId); return null; })) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(DataAccessException.class) + .hasMessageContaining( + "Tenant authority generation advance lacks its canonical source event"); assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) .isEqualTo(updated); assertThatThrownBy( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java index dc67f3cc10..cee232d476 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/AccountUuidTextTest.java @@ -1,9 +1,10 @@ -package net.firedevops.firemud.accountservice; +package unit.net.firedevops.firemud.accountservice; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountUuidText; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java index 6d2af29a7a..ffe6eb6ae7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.accountservice.service.impl; +package unit.net.firedevops.firemud.accountservice.service.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -17,6 +17,7 @@ import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.RuntimeAccountIdentityGrpcService; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.exception.TooManyRowsException; import org.junit.jupiter.api.Test; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java index 46bd45a5e0..c67be1058d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java @@ -275,12 +275,15 @@ void grpcCodecRoundTripsCompleteProofAndRejectsUnknownPartialOrChangedEcho() thr GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(pending))) .setPublishedPolicySetEvidence( ByteString.copyFrom(evidence.publishedPolicySetEvidence().canonicalBytes())) + .setAdmissionPointerSnapshotDigest(evidence.admissionPointerSnapshotDigest()) .build(); assertThatThrownBy( () -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( request, nonCommittedResponse)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "Game Session proof is not the exact current committed roster target"); } private static CanonicalGameplayRosterOwnerReadEvidence fixture() throws Exception { From f2d1b624bf8e418d8eb70e945536e60a420dd094 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:53:17 +1300 Subject: [PATCH 35/39] Deny bare JOIN authority baselines and verify deferred commit guard --- ...countMembershipAuthorityEventProducer.java | 33 +++++++++---------- ...EntitlementPersistenceIntegrationTest.java | 7 +++- ...thorityEventProducerCanonicalJoinTest.java | 24 ++++++++++++++ 3 files changed, 46 insertions(+), 18 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 3a4c21af14..c5332db93f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -385,21 +385,19 @@ private static Map membershipEventPreimage( "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), "outboxStreamKey", cutoff.outboxStreamKey(), "outboxSequence", cutoff.outboxSequence()))); - if (tenantSourceEvent != null) { - authorityTuple.put( - "tenantBillingCutoff", - Map.of( - tenantUuid.toString(), - Map.of( - "tenantAuthorityGeneration", - decimal(tenantSourceEvent.tenantAuthorityGeneration()), - "tenantBillingSequence", - decimal(tenantSourceEvent.tenantBillingSequence()), - "outboxStreamKey", - tenantSourceEvent.outboxStreamKey(), - "outboxSequence", - decimal(tenantSourceEvent.outboxSequence())))); - } + authorityTuple.put( + "tenantBillingCutoff", + Map.of( + tenantUuid.toString(), + Map.of( + "tenantAuthorityGeneration", + decimal(tenantSourceEvent.tenantAuthorityGeneration()), + "tenantBillingSequence", + decimal(tenantSourceEvent.tenantBillingSequence()), + "outboxStreamKey", + tenantSourceEvent.outboxStreamKey(), + "outboxSequence", + decimal(tenantSourceEvent.outboxSequence())))); Map event = new LinkedHashMap<>(); event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); @@ -641,7 +639,8 @@ private void requireCurrentAuthority( private TenantAuthorityEventV1Codec.Event readCurrentTenantSourceEvent( UUID tenantUuid, VerifiedTenantProvenance provenance, ScopeState tenantAuthority) { if (tenantAuthority.generation() == 1L && tenantAuthority.sourceVersion() == 1L) { - return null; + throw new IllegalStateException( + "Canonical first JOIN requires exact current public-JOIN entitlement and tenant authority evidence"); } TenantAuthorityEventV1Codec.Event event = tenantAuthorityEventRepository.readCurrentByTenant(tenantUuid); @@ -658,7 +657,7 @@ private static boolean tenantSourceEvidenceMatches( UUID tenantUuid, VerifiedTenantProvenance provenance) { if (event == null) { - return tenantAuthority.generation() == 1L && tenantAuthority.sourceVersion() == 1L; + return false; } var source = event.sourceEvidence(); return event.tenantId().equals(tenantUuid) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index 3a6e0148c3..712e84247c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -28,10 +28,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.support.TransactionTemplate; /** Physical PostgreSQL proof for exact-source demo entitlement commit and revalidation fencing. */ @@ -374,7 +376,10 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc tenantId); return null; })) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(TransactionSystemException.class) + .hasMessageContaining("JDBC commit failed") + .rootCause() + .isInstanceOf(PSQLException.class) .hasMessageContaining( "Tenant authority generation advance lacks its canonical source event"); assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 1a57bcfa16..59e9dab43b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -368,6 +368,30 @@ void firstJoinAcceptsLaterTenantAuthorityOnlyWithExactCurrentTenantSourceAndBill verify(fixture.tenantAuthorityEvents).readCurrentByTenant(TENANT_UUID); } + @Test + void firstJoinDeniesBareGenerationOneTenantBaselineBeforeEntitlementLookupOrMutation() { + Fixture fixture = new Fixture(); + fixture.arrangePendingFirstJoin(); + when(fixture.authority.readCompositeSnapshot( + "firemud-account-service", ACCOUNT_UUID, List.of(TENANT_UUID), List.of(TENANT_UUID))) + .thenReturn(fixture.authoritySnapshot(1L, 1L, 1L, 1L)); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical first JOIN requires exact current public-JOIN entitlement and tenant authority evidence"); + + verify(fixture.tenantAuthorityEvents, never()).readCurrentByTenant(TENANT_UUID); + verify(fixture.entitlements, never()).readCurrent(TENANT_UUID); + verify(fixture.outbox, never()) + .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); + verify(fixture.pairs, never()).commitTransition(any(), any()); + } + @Test void firstJoinDeniesAStalePendingEntitlementVersionWithoutMutation() { Fixture fixture = new Fixture(); From 0f6b57e8df44364e0d05d291f7b089e7de23868f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:45:16 +1300 Subject: [PATCH 36/39] test(common): extract shared authoring evidence fixtures --- .../WorldDraftTerminalReadGrpcCodecTest.java | 408 +--------------- .../common/testing/AuthoringFixtures.java | 445 ++++++++++++++++++ ...lishedRealmEntryPolicySetEvidenceTest.java | 3 +- ...ldPublishedStartLocationGrpcCodecTest.java | 58 +-- 4 files changed, 467 insertions(+), 447 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index 7d442beefc..5a4128f68b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -4,41 +4,29 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.UnknownFieldSet; -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; 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.testing.AuthoringFixtures; import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; import org.junit.jupiter.api.Test; public class WorldDraftTerminalReadGrpcCodecTest { - 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(); @@ -104,7 +92,7 @@ void independentlyDecodedByteEvidenceUsesCanonicalValueEquality() { binding.requiredOwners()); assertThat(changedSourceBinding).isNotEqualTo(binding); - var readback = committedReadback(request); + var readback = AuthoringFixtures.committedReadback(request); var decodedReadback = DraftAuthorizationFenceBinding.OwnerReadback.fromStored(readback.canonicalBytes()); assertThat(decodedReadback).isEqualTo(readback); @@ -235,7 +223,7 @@ void rejectsUnknownFieldsAndContradictoryStatusPayloads() { @Test void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSubstitution() { var request = request(); - var committed = committedReadback(request); + var committed = AuthoringFixtures.committedReadback(request); var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); assertThat(response.getStatus()) .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); @@ -331,7 +319,7 @@ void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSub void committedCarrierRejectsEmbeddedOperationGraphDigestEpochAndUnknownFieldChanges() throws Exception { var request = request(); - var committed = committedReadback(request); + var committed = AuthoringFixtures.committedReadback(request); var mapper = new tools.jackson.databind.ObjectMapper(); for (String field : List.of("operationBytesBase64", "graphDigest", "appliedEpochs", "unknown")) { @@ -365,8 +353,8 @@ void committedCarrierRejectsEmbeddedOperationGraphDigestEpochAndUnknownFieldChan @Test void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclaration() throws Exception { - var request = freshGraphRequest(); - var committed = committedReadback(request, true); + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); byte[] graphBytes = Base64.getDecoder().decode(object(committed.result()).get("graphBytesBase64").textValue()); assertThat(java.util.Arrays.equals(graphBytes, canonical(JSON.readTree(graphBytes)))).isFalse(); @@ -384,8 +372,8 @@ void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclarat @Test void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Exception { - var request = freshGraphRequest(); - var committed = committedReadback(request, true); + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); var result = object(committed.result()); result.put("graphDigest", "sha256:" + "0".repeat(64)); assertResultRejected(request, committed, canonical(result)); @@ -400,7 +388,7 @@ void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Excep DraftCommitBinding.fromStored( new String(request.accountBinding().gameDesignBinding(), StandardCharsets.UTF_8), request.accountBinding().inputDigest()); - var changedReceipt = receipt(request, draft, graphDigest); + var changedReceipt = AuthoringFixtures.receipt(request, draft, graphDigest); byte[] changedReceiptBytes = canonical(changedReceipt); result.put( "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); @@ -410,8 +398,8 @@ void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Excep @Test void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws Exception { - var request = freshGraphRequest(); - var committed = committedReadback(request, true); + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); for (java.util.function.Consumer change : List.>of( receipt -> @@ -449,8 +437,8 @@ void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws E @Test void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws Exception { - var request = freshGraphRequest(); - var committed = committedReadback(request, true); + var request = AuthoringFixtures.freshGraphRequest(); + var committed = AuthoringFixtures.committedFreshGraphReadback(request); var result = object(committed.result()); byte[] receiptBytes = Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); @@ -478,7 +466,7 @@ void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws var commitBinding = DraftCommitBinding.fromStored( new String(binding.gameDesignBinding(), StandardCharsets.UTF_8), binding.inputDigest()); - var changedReceipt = receipt(request, commitBinding, graphDigest); + var changedReceipt = AuthoringFixtures.receipt(request, commitBinding, graphDigest); byte[] changedReceiptBytes = canonical(JSON.valueToTree(changedReceipt)); result.put( "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); @@ -488,8 +476,8 @@ void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws @Test void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws Exception { - var declaredRequest = freshGraphRequest(); - var declaredResult = committedReadback(declaredRequest, true); + var declaredRequest = AuthoringFixtures.freshGraphRequest(); + var declaredResult = AuthoringFixtures.committedFreshGraphReadback(declaredRequest); var downgraded = object(declaredResult.result()); downgraded.put("schema", "world-draft-graph-applied/v1"); downgraded.remove("startLocationReceiptBase64"); @@ -497,7 +485,7 @@ void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws assertResultRejected(declaredRequest, declaredResult, canonical(downgraded)); var historicalRequest = request(); - var historicalResult = committedReadback(historicalRequest); + var historicalResult = AuthoringFixtures.committedReadback(historicalRequest); var upgraded = object(historicalResult.result()); upgraded.put("schema", "world-draft-graph-applied/v2"); upgraded.put( @@ -507,109 +495,6 @@ void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws assertResultRejected(historicalRequest, historicalResult, canonical(upgraded)); } - /** - * Transport-only stipulated carrier; real persistence and six-family semantics are World proof. - */ - static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( - WorldDraftTerminalReadEvidence.Request request) { - try { - return committedReadback(request, false); - } catch (Exception impossible) { - throw new AssertionError(impossible); - } - } - - 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 request() { return new WorldDraftTerminalReadEvidence.Request( 1, "test", uuid("33333333-3333-4333-8333-333333333333"), originalBinding()); @@ -634,264 +519,7 @@ private static byte[] originalBinding() { "ROOM_SCOPE", "room-1", "0"))); - return accountBinding(draft); - } - - /** Test-only exact fresh graph request shared with the published selector carrier proof. */ - public static WorldDraftTerminalReadEvidence.Request - freshGraphRequestForStartLocationEvidenceTest() throws Exception { - return freshGraphRequest(); - } - - /** Test-only complete World APPLIED-v2 readback for the exact fresh graph request. */ - public static DraftAuthorizationFenceBinding.OwnerReadback - committedFreshGraphReadbackForStartLocationEvidenceTest( - WorldDraftTerminalReadEvidence.Request request) { - try { - return committedReadback(request, true); - } catch (Exception impossible) { - throw new AssertionError(impossible); - } - } - - 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()); + return AuthoringFixtures.accountBinding(draft); } private static tools.jackson.databind.node.ObjectNode selector( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java new file mode 100644 index 0000000000..2774634468 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java @@ -0,0 +1,445 @@ +package net.firedevops.firemud.common.testing; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +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.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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Reusable exact authoring evidence fixtures for isolated Common carrier tests. */ +public final class AuthoringFixtures { + 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 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 ObjectMapper JSON = new ObjectMapper(); + + private AuthoringFixtures() {} + + public static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + public static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request) { + return committedReadback(request, false); + } + + public static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphReadback( + WorldDraftTerminalReadEvidence.Request request) { + return committedReadback(request, true); + } + + public static WorldPublishedStartLocationEvidence startLocationEvidence() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + var committed = committedFreshGraphReadback(terminalRequest); + 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()); + } + + public 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(); + } + + public static 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 (ObjectNode) JSON.valueToTree(value); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) { + try { + 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))); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + + 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[] 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 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 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); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index a0bf6a573c..23a4df5eaf 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.testing.AuthoringFixtures; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; @@ -639,7 +640,7 @@ static ReleaseContent release( } static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { - var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); + var seed = AuthoringFixtures.startLocationEvidence(); var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var draft = DraftCommitBinding.fromStored( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java index e39fab893d..e62f3dd8c2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -4,21 +4,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.ByteString; -import java.nio.charset.StandardCharsets; -import java.util.Base64; import java.util.List; import java.util.UUID; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; -import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; -import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.testing.AuthoringFixtures; import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; import org.junit.jupiter.api.Test; class WorldPublishedStartLocationGrpcCodecTest { private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; - private static final tools.jackson.databind.ObjectMapper JSON = - new tools.jackson.databind.ObjectMapper(); @Test void exactSelectionAndRetainedEvidenceRoundTripAcrossReadRetries() throws Exception { @@ -164,54 +157,7 @@ void requestCarrierAcceptsUnboundedDraftEpochAndRejectsMalformedCounters() throw } static WorldPublishedStartLocationEvidence evidence() throws Exception { - WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); - OwnerReadback committed = freshGraphReadback(terminalRequest); - 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 WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { - return WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); - } - - private static OwnerReadback freshGraphReadback(WorldDraftTerminalReadEvidence.Request request) - throws Exception { - return WorldDraftTerminalReadGrpcCodecTest - .committedFreshGraphReadbackForStartLocationEvidenceTest(request); + return AuthoringFixtures.startLocationEvidence(); } private static UUID uuid(String value) { From af682a9517bb6fc061903cf51538c1ffbe94124b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:30:03 +1300 Subject: [PATCH 37/39] test: verify precise authoring rejection paths and explain dependency refresh --- .github/workflows/ci.yml | 1 + .../WorldDraftTerminalReadGrpcCodecTest.java | 163 ++++++++++++++++-- 2 files changed, 146 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5cf5d4fe10..f16734644e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -988,6 +988,7 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false + # Cached negative Spring Boot 4.1.1 resolution requires metadata revalidation (CI 37847761035). - name: 🧪 Run Gradle Checks id: checks run: | diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index 5a4128f68b..30dc76b1c9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashSet; @@ -17,6 +18,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; import org.junit.jupiter.api.Test; @@ -376,7 +379,8 @@ void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Excep var committed = AuthoringFixtures.committedFreshGraphReadback(request); var result = object(committed.result()); result.put("graphDigest", "sha256:" + "0".repeat(64)); - assertResultRejected(request, committed, canonical(result)); + assertResultRejected( + request, committed, canonical(result), "World APPLIED carrier differs at graphDigest"); result = object(committed.result()); byte[] malformedGraph = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); @@ -393,7 +397,7 @@ void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Excep result.put( "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); - assertResultRejected(request, committed, canonical(result)); + assertResultRejected(request, committed, canonical(result), CharacterCodingException.class); } @Test @@ -421,22 +425,41 @@ void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws E uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), receipt -> receipt.put("accountBindingDigest", "sha256:" + "0".repeat(64)), receipt -> receipt.put("bindingDigest", "sha256:" + "0".repeat(64)), - receipt -> receipt.put("graphDigest", "sha256:" + "0".repeat(64)), - receipt -> receipt.put("receiptDigest", "sha256:" + "0".repeat(64)))) { - assertReceiptChangeRejected(request, committed, change); + receipt -> receipt.put("graphDigest", "sha256:" + "0".repeat(64)))) { + assertReceiptChangeRejected( + request, + committed, + change, + "World start-location receipt differs from its original Account-bound graph", + true); } assertReceiptChangeRejected( - request, committed, receipt -> receipt.put("unsupported", "new-field")); + request, + committed, + receipt -> receipt.put("receiptDigest", "sha256:" + "0".repeat(64)), + "World start-location receipt digest is invalid", + false); + assertReceiptChangeRejected( + request, + committed, + receipt -> receipt.put("unsupported", "new-field"), + "World start-location receipt has missing or unsupported fields", + true); var changedTopLevel = object(committed.result()); changedTopLevel.put("unsupported", "new-field"); - assertResultRejected(request, committed, canonical(changedTopLevel)); + assertResultRejected( + request, committed, canonical(changedTopLevel), "World APPLIED carrier fields differ"); changedTopLevel = object(committed.result()); changedTopLevel.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); - assertResultRejected(request, committed, canonical(changedTopLevel)); + assertResultRejected( + request, + committed, + canonical(changedTopLevel), + "World APPLIED carrier differs at startLocationReceiptDigest"); } @Test - void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws Exception { + void v2RejectsNoncanonicalReceiptBytesAndGraphRevisionSubstitution() throws Exception { var request = AuthoringFixtures.freshGraphRequest(); var committed = AuthoringFixtures.committedFreshGraphReadback(request); var result = object(committed.result()); @@ -446,7 +469,8 @@ void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws result.put( "startLocationReceiptBase64", Base64.getEncoder().encodeToString((" " + receiptJson).getBytes(StandardCharsets.UTF_8))); - assertResultRejected(request, committed, canonical(result)); + assertResultRejected( + request, committed, canonical(result), "World start-location receipt is not canonical"); result = object(committed.result()); byte[] graphBytes = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); @@ -471,7 +495,12 @@ void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws result.put( "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); - assertResultRejected(request, committed, canonical(result)); + // The exact ordered original revision check subsumes the later selected-ROOM presence guard. + assertResultRejected( + request, + committed, + canonical(result), + "World v2 graph row differs from its exact original revision"); } @Test @@ -482,9 +511,13 @@ void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws downgraded.put("schema", "world-draft-graph-applied/v1"); downgraded.remove("startLocationReceiptBase64"); downgraded.remove("startLocationReceiptDigest"); - assertResultRejected(declaredRequest, declaredResult, canonical(downgraded)); + assertResultRejected( + declaredRequest, + declaredResult, + canonical(downgraded), + "Historical World APPLIED v1 cannot downgrade a declared fresh graph"); - var historicalRequest = request(); + var historicalRequest = requestWithUndeclaredWorldGraph(); var historicalResult = AuthoringFixtures.committedReadback(historicalRequest); var upgraded = object(historicalResult.result()); upgraded.put("schema", "world-draft-graph-applied/v2"); @@ -492,7 +525,45 @@ void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws "startLocationReceiptBase64", Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); upgraded.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); - assertResultRejected(historicalRequest, historicalResult, canonical(upgraded)); + assertResultRejected( + historicalRequest, + historicalResult, + canonical(upgraded), + "World v2 requires an original complete graph declaration"); + } + + private static WorldDraftTerminalReadEvidence.Request requestWithUndeclaredWorldGraph() { + String revisionPayload = + "{\"logicalRevisionId\":\"" + + REVISION_ID + + "\",\"commitId\":\"" + + COMMIT_ID + + "\",\"aggregateType\":\"WORLD_DESIGN_AGGREGATE_TYPE_ROOM\",\"aggregateId\":\"" + + uuid("77777777-7777-4777-8777-777777777777") + + "\"}"; + DraftCommitBinding draft = + 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", REVISION_ID, DraftCommitBinding.Owner.WORLD_MANAGEMENT, revisionPayload)), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + return new WorldDraftTerminalReadEvidence.Request( + 1, + "test", + uuid("33333333-3333-4333-8333-333333333333"), + AuthoringFixtures.accountBinding(draft)); } private static WorldDraftTerminalReadEvidence.Request request() { @@ -530,21 +601,68 @@ private static tools.jackson.databind.node.ObjectNode selector( private static void assertReceiptChangeRejected( WorldDraftTerminalReadEvidence.Request request, DraftAuthorizationFenceBinding.OwnerReadback committed, - java.util.function.Consumer change) + java.util.function.Consumer change, + String expectedRootCause, + boolean recalculateReceiptDigest) throws Exception { var result = object(committed.result()); byte[] bytes = Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); var receipt = object(bytes); change.accept(receipt); + if (recalculateReceiptDigest) recalculateReceiptDigest(receipt); result.put( "startLocationReceiptBase64", Base64.getEncoder().encodeToString(canonical(receipt))); - assertResultRejected(request, committed, canonical(result)); + assertResultRejected(request, committed, canonical(result), expectedRootCause); + } + + private static void recalculateReceiptDigest(tools.jackson.databind.node.ObjectNode receipt) { + var selector = selector(receipt); + var evidence = + WorldDraftStartLocationEvidence.create( + receipt.get("targetNamespace").textValue(), + uuid(receipt.get("operationId").textValue()), + uuid(receipt.get("requestId").textValue()), + uuid(receipt.get("commitId").textValue()), + uuid(receipt.get("authorizationFenceId").textValue()), + receipt.get("accountBindingDigest").textValue(), + receipt.get("bindingDigest").textValue(), + new RoomTemplateRef( + uuid(selector.get("tenantId").textValue()), + uuid(selector.get("versionId").textValue()), + uuid(selector.get("roomTemplateId").textValue())), + receipt.get("graphDigest").textValue()); + receipt.put("receiptDigest", evidence.receiptDigest()); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes, + String expectedRootCauseMessage) { + assertResultRejected( + request, + committed, + resultBytes, + cause -> assertThat(cause).hasMessageContaining(expectedRootCauseMessage)); } private static void assertResultRejected( WorldDraftTerminalReadEvidence.Request request, DraftAuthorizationFenceBinding.OwnerReadback committed, - byte[] resultBytes) { + byte[] resultBytes, + Class expectedRootCauseType) { + assertResultRejected( + request, + committed, + resultBytes, + cause -> assertThat(cause).isInstanceOf(expectedRootCauseType)); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes, + java.util.function.Consumer assertRootCause) { var baseline = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); var substituted = readbackWithResult(committed, resultBytes); var response = @@ -553,7 +671,16 @@ private static void assertResultRejected( com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) .build(); assertThatThrownBy(() -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, response)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "World committed readback has an invalid or substituted canonical APPLIED result") + .satisfies(exception -> assertRootCause.accept(rootCause(exception))); + } + + private static Throwable rootCause(Throwable exception) { + Throwable cause = exception; + while (cause.getCause() != null) cause = cause.getCause(); + return cause; } private static DraftAuthorizationFenceBinding.OwnerReadback readbackWithResult( From 17e9b80a1afa256b3240743567b6e24a3f7492a1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:03:09 +1300 Subject: [PATCH 38/39] fix: reject launch results contradicting explicit selection --- ...AuthoredWorldLaunchDescriptorEvidence.java | 9 ++ ...oredWorldLaunchDescriptorEvidenceTest.java | 124 ++++++++++++++++++ 2 files changed, 133 insertions(+) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java index 4f9c3aab1d..4aeeedd38a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -122,6 +122,15 @@ public String requestDigest() { requireOptional(remapSetIdPresent, remapSetId, "remapSetId"); requireText(launchDescriptorId, "launchDescriptorId"); requirePositive(versionId, "versionId"); + if (targetVersionIdPresent && targetVersionId.longValue() != versionId) { + throw new IllegalArgumentException("Resolved versionId does not match the requested target"); + } + if (requestedScriptPatchVersionPresent + && (!scriptPatchVersionPresent + || !requestedScriptPatchVersion.equals(scriptPatchVersion))) { + throw new IllegalArgumentException( + "Resolved scriptPatchVersion does not match the requested override"); + } requireText(runtimeFlagsJson, "runtimeFlagsJson"); requireText(generationConfigRevision, "generationConfigRevision"); if (versionStateEpoch <= 0) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java index f2de396131..70aa8b0d2e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidenceTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamedesign; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -42,6 +43,129 @@ void digestsHashTheExactPreimagesAndKeepTheirCurrentVectors() throws NoSuchAlgor assertThat(evidence.resultDigest()).isEqualTo(RESULT_DIGEST); } + @Test + void factoryRejectsResultsThatContradictRequestedTargetOrPatch() { + AuthoredWorldLaunchDescriptorEvidence.Request targetRequest = request(42L, false, null); + AuthoredWorldLaunchDescriptorEvidence.Request patchRequest = + request(null, true, "requested-patch"); + + assertThatThrownBy(() -> create(targetRequest, 43L, false, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested target"); + assertThatThrownBy(() -> create(patchRequest, 42L, false, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + assertThatThrownBy(() -> create(patchRequest, 42L, true, "different-patch")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + } + + @Test + void directConstructionRejectsResultsThatContradictRequestedTargetOrPatch() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request(42L, true, "requested-patch"); + AuthoredWorldLaunchDescriptorEvidence valid = create(request, 42L, true, "requested-patch"); + + assertThatThrownBy(() -> copyWithResult(valid, 43L, true, "requested-patch")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested target"); + assertThatThrownBy(() -> copyWithResult(valid, 42L, false, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + assertThatThrownBy(() -> copyWithResult(valid, 42L, true, "different-patch")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requested override"); + } + + @Test + void acceptsExactOverridesAndServerSelectedDefaults() { + AuthoredWorldLaunchDescriptorEvidence exactOverride = + create(request(42L, true, "requested-patch"), 42L, true, "requested-patch"); + AuthoredWorldLaunchDescriptorEvidence selectedDefault = + create(request(42L, false, null), 42L, true, "template-default-patch"); + + assertThat(exactOverride.versionId()).isEqualTo(42L); + assertThat(exactOverride.scriptPatchVersion()).isEqualTo("requested-patch"); + assertThat(selectedDefault.versionId()).isEqualTo(42L); + assertThat(selectedDefault.scriptPatchVersion()).isEqualTo("template-default-patch"); + } + + private static AuthoredWorldLaunchDescriptorEvidence create( + AuthoredWorldLaunchDescriptorEvidence.Request request, + long versionId, + boolean patchPresent, + String patch) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + versionId, + patchPresent, + patch, + "{}", + "generation-config", + 9L, + 7L, + "published-release", + false, + null); + } + + private static AuthoredWorldLaunchDescriptorEvidence copyWithResult( + AuthoredWorldLaunchDescriptorEvidence evidence, + long versionId, + boolean patchPresent, + String patch) { + return new AuthoredWorldLaunchDescriptorEvidence( + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.controlPlaneRequestId(), + evidence.canonicalTenantId(), + evidence.worldSlug(), + evidence.authoredWorldSourceOperationId(), + evidence.authoredWorldSourceEvidenceDigest(), + evidence.gameTemplateId(), + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion(), + evidence.sourceVersionIdPresent(), + evidence.sourceVersionId(), + evidence.targetVersionIdPresent(), + evidence.targetVersionId(), + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson(), + evidence.requestDigest(), + evidence.launchDescriptorId(), + versionId, + patchPresent, + patch, + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetIdPresent(), + evidence.remapSetId(), + evidence.resultDigest()); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request( + Long targetVersionId, boolean patchPresent, String patch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "synthetic-world", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + patchPresent, + patch, + false, + null, + targetVersionId != null, + targetVersionId, + false, + null); + } + private static AuthoredWorldLaunchDescriptorEvidence.Request request() { return new AuthoredWorldLaunchDescriptorEvidence.Request( "test", From 3431a211a5cfba1f7b2e51456e16f814b9d2ef9b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:09:11 +1300 Subject: [PATCH 39/39] test: stabilize fresh authoring graph declaration bytes --- .../common/testing/AuthoringFixtures.java | 39 ++++++++++++------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java index 2774634468..897e2d90f4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java @@ -4,6 +4,7 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -261,28 +262,27 @@ private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( } private static DraftCommitBinding freshGraphBinding() throws Exception { + List> familyCounts = + List.of( + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + insertionOrderedMap( + "family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + insertionOrderedMap( + "family", "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", "count", 0)); String declaration = JSON.writeValueAsString( - Map.of( + insertionOrderedMap( "tenantId", TENANT_ID.toString(), "versionId", VERSION_ID.toString(), "startLocation", - Map.of( + insertionOrderedMap( "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)))); + "familyCounts", familyCounts)); return DraftCommitBinding.create( new TargetProof( TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), @@ -320,6 +320,17 @@ private static DraftCommitBinding freshGraphBinding() throws Exception { .toList()); } + private static Map insertionOrderedMap(Object... entries) { + if (entries.length % 2 != 0) { + throw new IllegalArgumentException("Map entries must be key-value pairs"); + } + Map result = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + result.put((String) entries[index], entries[index + 1]); + } + return result; + } + private static String worldRevisionPayload( UUID revisionId, String family, UUID templateId, String declaration) throws Exception { var payload = new java.util.LinkedHashMap();