From ada9df77752e1c2698e233f1d1395ecb33a1f000 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:40:58 +1300 Subject: [PATCH 01/28] feat(entity): retain actor identity quarantine and deny unproved consumers --- .../entity-management-service/README.md | 4 +- .../entity-management-service/operations.md | 68 + .../runtime-and-data.md | 24 +- .../gameplay-rules-entities-and-effects.md | 12 +- .../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 | 93 +- .../RetainedActorIdentityIntegrationTest.java | 1253 +++++++++++++++++ ...FlywayPostgresqlLockConfigurationTest.java | 57 + .../entity/ActorIdentityValueTest.java | 108 ++ .../ActorActiveConditionRepositoryTest.java | 120 ++ .../ActorResourceStateRepositoryTest.java | 117 ++ .../CharacterFriendRepositoryTest.java | 133 ++ ...arantinedActorRetentionRepositoryTest.java | 89 ++ .../service/ScopedCharacterResolverTest.java | 46 + .../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 + 42 files changed, 3102 insertions(+), 275 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/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/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.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/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/CharacterFriendRepositoryTest.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/ScopedCharacterResolverTest.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/README.md b/design/architecture/microservices/entity-management-service/README.md index ee6c681fd2..6f3989b11b 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. +Persisted rows and realm-aware listing code exist. V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Unit and fixture proof limits, including the absence of physical PostgreSQL and authenticated Game Session-to-Entity network proof, are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). + +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/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 8e18a05c8f..af6540016a 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -10,6 +10,74 @@ 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 only the statement for the specific index confirmed invalid and unattached; each statement must run outside a transaction. + +Only if inspection confirms `ux_characters_character_uuid_idx` is invalid, unattached, and matches the expected V3 definition: + +```sql +DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".ux_characters_character_uuid_idx; +``` + +Only if inspection independently confirms `idx_characters_owner_resolved_roster` is invalid, unattached, and matches the expected V3 definition: + +```sql +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. + +Dropping invalid, unattached indexes does not remove the failed V3 entry from Flyway history. Only when exact post-cleanup inspection proves that both `ux_characters_character_uuid_idx` and `idx_characters_owner_resolved_roster` indexes and the `ux_characters_character_uuid` constraint are absent, repair the failed V3 history entry in the owning Entity schema/history table before rerunning migrate, keeping writer admission closed and writers quiesced throughout. Any surviving valid object or mixed state still requires the operator-reviewed, phase-specific roll-forward plan above. + ## 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 b9eaa2b9eb..8932fc1501 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -11,14 +11,17 @@ 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. -- 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. +- Entity's standard, production, and test 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 historical full-source integration evidence and remaining gaps; this Stage 1 split has not been validated. +- 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. +- Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Current execution and proof status is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); physical PostgreSQL and authenticated Game Session-to-Entity mTLS/network proof are not claimed. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. +- Legacy character roster/name lookup paths 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. The original full-source container-location fixture and conditional service tests use explicitly mocked test guards; this Stage 1 split has no integration proof for those downstream paths and does not establish 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. - 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. -- 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 @@ -102,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. @@ -123,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 { @@ -140,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: @@ -303,7 +309,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 @@ -417,7 +423,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 f2167c082c..a722fafc45 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 @@ -12,7 +12,7 @@ Current residual: the crafting handlers remain runtime-reachable legacy implemen The capability-table CRUD entry below refers only to this legacy persistence/service-controller seam; it is not a supported public REST API or gameplay crafting flow. -PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). Gameplay tracking retains only the consequence that actor-state/effect work must use Entity's persisted realm-valid identity; current synthetic-ID, fixed-schema, policy-resolution, provisioning, and fork-copy proof gaps remain. +PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). Stage 1 adds Entity-owned opaque character identity, quarantine for unresolved legacy provenance, and fail-closed legacy consumers; it does not establish owner provenance, identity promotion, gameplay admission, or PLAY. PRESEEDED_ONLY assignment and owner-qualified roster/receipt source evidence remain in the following stage. Gameplay tracking retains only the consequence that actor-state/effect work must use Entity's persisted realm-valid identity; current synthetic-ID, fixed-schema, policy-resolution, provisioning, and fork-copy proof gaps remain. Passive `CHARACTER_CREATE/1` receiving support is now present in common-platform-core: [the family codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java) composes the existing `MutationDigestV1` grammar with schema-three `RealmEntryPolicy`; its bounded [authored-source projection parser](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) checks the retained `GameplayRuleManifest` and `PlayerCreationDescriptor` inputs. The [shared vector resource](../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) retains four literal positive preimages and now includes required negative cases; the [focused codec test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java) exercises the production decoder against those fixtures and checks additional source contradictions. The current local run and its limits are recorded under [Validation and Proof](#validation-and-proof). This remains local-only receiver support: it does not establish a Game Session producer, authenticated source readback, Entity terminal or owner protections, or route activation, so GR-3.1 remains partial. The [canonical family schema](../../architecture/microservices/entity-management-service/character-create-action-schema.md) owns the contract details. @@ -28,12 +28,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` - 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. Passive `CHARACTER_CREATE/1` codec and authored-source projection receiving support is present. | `proven` - focused character, NPC, item/inventory, and passive character-action tests cover bounded records, lifecycle, and receiving seams, not PLAYER-01 owner protection or activation 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); [CharacterCreateOperatorActionCodec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java); [AuthoredInitialActorCoreProjection.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) | [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); [CharacterCreateOperatorActionCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.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 is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `partial` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. Historical full-source e3 evidence records a local combined Entity run with 291 passing unit tests and an exact-head [hosted Entity integration-test job](https://github.com/benhook1013/FireMUD/actions/runs/37868666749/job/113621467457); the log records actual `:entity-management-service:integrationTest` execution and `BUILD SUCCESSFUL` in 5m49, with no executed-case count artifact. That full-source run also includes PostgreSQL-backed receiver integration proof, but none of it is exact-head proof for this split postimage. Split-specific compilation/tests, authenticated Game Session-to-Entity mTLS/network proof, and live PLAY proof are unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | +| 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` 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 bypasses the Entity replay ledger. | `partial` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. This split has not been validated. | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, 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 code exists, but production actor-scoped equipment admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment service/controller and item-command tests cover slot compatibility and binding, not production owner-qualified actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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. Owner-qualified runtime admission, 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 the self-targeted `APPLY_ACTION_STATE` command path exist, but scoped Entity actor-state/effect access 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; receiver test execution and proof status are recorded under GR-3.1. | [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 owner-qualified 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 read code exist, but production XP/level mutation and actor-state reads remain fail-closed pending owner-qualified actor resolution; ability and skill progression is not implemented. | `audited` - focused character progression and actor-state tests cover the bounded XP/level seam with a mocked resolver; this conditional service 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/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..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 @@ -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) @@ -87,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; } @@ -109,10 +126,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..83de1b6c5c --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java @@ -0,0 +1,105 @@ +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 478bd81341..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 @@ -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,14 @@ 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(ownerResolvedActorExists())) .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) @@ -54,20 +58,57 @@ 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; } + 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 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..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 @@ -1,14 +1,17 @@ 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; @@ -25,10 +28,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 +51,26 @@ 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) { + 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()) @@ -69,10 +88,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..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 @@ -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.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"); } - 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..eea689b28b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java @@ -0,0 +1,90 @@ +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 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..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,34 +1,18 @@ 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.RoomGroundInventoryRepository; +import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; 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) { - this.roomGroundInventoryRepository = roomGroundInventoryRepository; - this.itemStackRepository = itemStackRepository; - this.itemInstanceRepository = itemInstanceRepository; - this.containerInstanceRepository = containerInstanceRepository; + QuarantinedActorRetentionRepository quarantinedActorRetentionRepository) { + this.quarantinedActorRetentionRepository = quarantinedActorRetentionRepository; } @Override @@ -44,19 +28,11 @@ public RuntimeInstanceCleanupResultDto cleanupRuntimeInstance( if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } - 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); + 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); } } 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..3e6052e2ea 100644 --- a/services/entity-management-service/src/main/resources/application-prod.yml +++ b/services/entity-management-service/src/main/resources/application-prod.yml @@ -7,6 +7,8 @@ spring: schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} + postgresql: + transactional-lock: false placeholders: serviceSchema: ${SERVICE_SCHEMA:public} ssl: diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index d3b5e99641..6770b26bf7 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -7,6 +7,8 @@ spring: locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} table: ${SPRING_FLYWAY_TABLE:flyway_schema_history_${SERVICE_SCHEMA:public}} + postgresql: + transactional-lock: false placeholders: serviceSchema: ${SERVICE_SCHEMA:public} ssl: 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..2022ded057 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql @@ -0,0 +1,172 @@ +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 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..0a927a7853 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql @@ -0,0 +1,34 @@ +/* [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 c93c1e6813..1ad440f8a1 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,10 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +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,17 +16,18 @@ 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; import org.springframework.data.domain.Pageable; 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; @@ -31,6 +36,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( @@ -38,11 +49,12 @@ classes = EntityManagementServiceApplication.class, properties = "spring.grpc.server.port=0") class ContainerInstanceLocationIntegrationTest { - private static final Long TENANT_ID = 1L; + private Long tenantId; private static final String GAME_INSTANCE_ID = "GI-1"; 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 = @@ -66,31 +78,55 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private ItemInstanceRepository itemInstanceRepository; @Autowired private ItemStackRepository itemStackRepository; @Autowired private ContainerInstanceRepository containerInstanceRepository; - @Autowired private JdbcTemplate jdbcTemplate; - @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private ScopedCharacterResolver scopedCharacterResolver; @BeforeEach void cleanDatabase() { - jdbcTemplate.execute( - "TRUNCATE TABLE item_stacks, item_instances, container_instances, items, characters RESTART IDENTITY CASCADE"); + tenantId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + 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 (!this.tenantId.equals(tenantId) + || !GAME_INSTANCE_ID.equals(gameInstanceId) + || PLAYABLE_STATE_SCOPE != playableStateScope + || character == null + || !this.tenantId.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)); } @Test 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")); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 1); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); var inventory = inventoryService.listInventory( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); var backpackEntry = inventory.getContent().stream() .filter(entry -> entry.itemId().equals(backpack.getId())) @@ -103,7 +139,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { .orElseThrow(); containerService.putItemIntoContainer( - TENANT_ID, + tenantId, alice.getId(), backpackEntry.containerInstanceId(), GAME_INSTANCE_ID, @@ -117,7 +153,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { null); inventoryService.dropItemToRoom( - TENANT_ID, + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, @@ -132,7 +168,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { var roomGround = inventoryService.listRoomGroundItems( - TENANT_ID, GAME_INSTANCE_ID, ROOM_INSTANCE_ID, Pageable.unpaged()); + tenantId, GAME_INSTANCE_ID, ROOM_INSTANCE_ID, Pageable.unpaged()); var droppedBackpack = roomGround.getContent().stream() .filter(entry -> entry.itemId().equals(backpack.getId())) @@ -144,7 +180,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { var roomContents = containerService.listContainerContents( - TENANT_ID, + tenantId, alice.getId(), backpackEntry.containerInstanceId(), GAME_INSTANCE_ID, @@ -156,7 +192,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { .satisfies(item -> assertThat(item.itemName()).isEqualTo("Torch")); inventoryService.pickupItemFromRoom( - TENANT_ID, + tenantId, bob.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, @@ -171,7 +207,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { var bobContents = containerService.listContainerContents( - TENANT_ID, + tenantId, bob.getId(), backpackEntry.containerInstanceId(), GAME_INSTANCE_ID, @@ -186,20 +222,21 @@ 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")); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 2); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 2); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, ration.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, ration.getId(), 1); var inventory = inventoryService.listInventory( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); var backpacks = inventory.getContent().stream() .filter(entry -> entry.itemId().equals(backpack.getId())) @@ -220,7 +257,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { .isNotEqualTo(backpacks.get(1).containerInstanceId()); containerService.putItemIntoContainer( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(0).containerInstanceId(), GAME_INSTANCE_ID, @@ -233,7 +270,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { null, null); containerService.putItemIntoContainer( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(1).containerInstanceId(), GAME_INSTANCE_ID, @@ -248,7 +285,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { var firstContents = containerService.listContainerContents( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(0).containerInstanceId(), GAME_INSTANCE_ID, @@ -257,7 +294,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { Pageable.unpaged()); var secondContents = containerService.listContainerContents( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(1).containerInstanceId(), GAME_INSTANCE_ID, @@ -275,7 +312,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { private Character character(String name) { Character character = new Character(); - character.setTenantId(TENANT_ID); + character.setTenantId(tenantId); character.setAccountId((long) name.length() + 1L); character.setPlayableStateKey("shared-live"); character.setName(name); @@ -291,6 +328,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); @@ -299,7 +342,7 @@ private Item containerItem(String name) { private Item ordinaryItem(String name) { Item item = new Item(); - item.setTenantId(TENANT_ID); + item.setTenantId(tenantId); item.setVersionId(1L); item.setName(name); item.setDescription(name + " desc"); 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..2ee426ee4f --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -0,0 +1,1253 @@ +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.ThreadLocalRandom; +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.InventoryService; +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.TestInfo; +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 long tenantId; + private long accountId; + private String instanceId; + private UUID tenantUuid; + private UUID accountUuid; + private UUID namespaceUuid; + private long fixtureIdOffset; + 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 InventoryService inventoryService; + @Autowired private ScopedCharacterResolver scopedCharacterResolver; + @Autowired private CharacterService characterService; + @Autowired private JdbcTemplate jdbcTemplate; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @BeforeEach + void allocateIsolatedFixtureIdentities(TestInfo testInfo) { + fixtureIdOffset = fixtureIdOffset(testInfo.getTestMethod().orElseThrow().getName()); + tenantId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + accountId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + instanceId = "GI-RETAINED-" + UUID.randomUUID(); + tenantUuid = UUID.randomUUID(); + accountUuid = UUID.randomUUID(); + namespaceUuid = UUID.randomUUID(); + } + + private long fixtureIdOffset(String testMethodName) { + return switch (testMethodName) { + case "canonicalRosterMatchesExactOwnerIdentityAndExcludesLegacyQuarantine" -> 100_000L; + case "namespaceIdentityAndScopeAreImmutableWithoutActorReferences" -> 200_000L; + case "quarantinedActorLookupMutationExpiryAndCleanupRemainHeld" -> 300_000L; + case "destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows" -> 400_000L; + case "destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows" -> 500_000L; + case "unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping" -> 600_000L; + case "flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints" -> 700_000L; + case "characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch" -> 800_000L; + default -> throw new IllegalArgumentException("No fixture ID range for " + testMethodName); + }; + } + + private long fixtureId(long localId) { + return fixtureIdOffset + localId; + } + + @Test + void canonicalRosterMatchesExactOwnerIdentityAndExcludesLegacyQuarantine() { + insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + UUID legacyActorUuid = UUID.randomUUID(); + UUID ownerResolvedActorUuid = UUID.randomUUID(); + long legacyId = + insertActor( + "legacy-shared", + legacyActorUuid, + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId); + + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat(characterRepository.findByIdAndTenantId(legacyId, tenantId)).isEmpty(); + + insertActor( + "owner-resolved", + ownerResolvedActorUuid, + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + var roster = + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(roster) + .extracting(identity -> identity.characterUuid()) + .containsExactly(ownerResolvedActorUuid); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ownerResolvedActorUuid.toString())) + .get() + .extracting(identity -> identity.characterUuid()) + .isEqualTo(ownerResolvedActorUuid); + + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + UUID.randomUUID().toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + UUID.randomUUID().toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + accountUuid.toString(), + UUID.randomUUID().toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + legacyActorUuid.toString())) + .isEmpty(); + + assertThatThrownBy( + () -> + actorIdentityRepository.findOwnerResolvedRoster( + null, + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + accountUuid.toString(), + "not-a-uuid", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), + "00000000-0000-0000-0000-000000000000", + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + insertNamespace( + tenantUuid, namespaceUuid, 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(), + tenantUuid, + namespaceUuid)) + .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(tenantId); + actor.setAccountId(accountId); + actor.setPlayableStateKey("instance:" + instanceId); + 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(tenantId); + resourceWrite.setCharacterId(actorId); + resourceWrite.setPlayableStateKey("instance:" + instanceId); + 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(tenantId); + conditionWrite.setCharacterId(actorId); + conditionWrite.setPlayableStateKey("instance:" + instanceId); + 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 " + + "(" + + fixtureId(3001) + + ", 'Backpack', ?, true), (" + + fixtureId(3002) + + ", 'Pouch', ?, true), (" + + fixtureId(3003) + + ", 'Gem', ?, false)", + tenantId, + tenantId, + tenantId); + jdbcTemplate.update( + "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (?, " + + fixtureId(3003) + + ", 5, 2)", + actorId); + jdbcTemplate.update( + "INSERT INTO character_equipment (character_id, slot, item_id, version) " + + "VALUES (?, 'hand', " + + fixtureId(3003) + + ", 3)", + actorId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) " + + "VALUES (?, ?, ?, 'pending')", + actorId, + actorId, + tenantId); + 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)", + tenantId, + actorId, + "instance:" + instanceId); + 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)", + tenantId, + actorId, + "instance:" + instanceId); + + jdbcTemplate.update( + "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) " + + "VALUES (" + + fixtureId(3101) + + ", ?, ?, ?, " + + fixtureId(3001) + + ", 6)", + tenantId, + actorId, + instanceId); + insertItemInstance( + fixtureId(3201), actorId, instanceId, null, fixtureId(3001), "retained-backpack"); + jdbcTemplate.update( + "UPDATE container_instances SET item_instance_id = ? WHERE id = ?", + fixtureId(3201), + fixtureId(3101)); + insertItemInstance( + fixtureId(3202), null, instanceId, fixtureId(3101), fixtureId(3002), "retained-pouch"); + jdbcTemplate.update( + "INSERT INTO container_instances (id, tenant_id, game_instance_id, item_id, version, item_instance_id) " + + "VALUES (" + + fixtureId(3102) + + ", ?, ?, " + + fixtureId(3002) + + ", 7, " + + fixtureId(3202) + + ")", + tenantId, + instanceId); + insertItemInstance( + fixtureId(3203), null, instanceId, fixtureId(3102), fixtureId(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 (" + + fixtureId(3301) + + ", ?, ?, ?, " + + fixtureId(3003) + + ", 'actor-stack', 8, 2, 'actor-family')", + tenantId, + actorId, + instanceId); + 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 (" + + fixtureId(3302) + + ", ?, ?, " + + fixtureId(3102) + + ", " + + fixtureId(3003) + + ", 'nested-stack', 9, 3, 'nested-family')", + tenantId, + instanceId); + jdbcTemplate.update( + "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " + + "VALUES (?, ?, 'room-retained', " + + fixtureId(3003) + + ", 11, 8)", + tenantId, + instanceId); + 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 (" + + fixtureId(3401) + + ", ?, " + + fixtureId(3001) + + ", " + + fixtureId(3201) + + ", 1, 'DROP', ?, 'effect-retained', 'corr-retained', 'CHARACTER', ?, ?, 'ROOM', ?, 'room-retained')", + tenantId, + actorId, + actorId, + instanceId, + instanceId); + jdbcTemplate.update( + "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) " + + "VALUES (" + + fixtureId(3501) + + ", ?, 'effect-retained', 'DROP', 'DropResponse', decode('aabb', 'hex'), 'APPLIED')", + tenantId); + + assertThatThrownBy( + () -> + scopedCharacterResolver.requireScopedCharacter( + tenantId, + actorId, + instanceId, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); + Map holderCountsBeforeRejectedAdd = inventoryHolderMutationCounts(actorId); + assertThatThrownBy( + () -> + inventoryService.addItem( + tenantId, + actorId, + instanceId, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + fixtureId(3001), + 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); + assertThat(inventoryHolderMutationCounts(actorId)).isEqualTo(holderCountsBeforeRejectedAdd); + assertThatThrownBy( + () -> + characterService.gainExperience( + tenantId, + actorId, + instanceId, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + 100)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + runtimeInstanceCleanupService.cleanupRuntimeInstance( + tenantId, instanceId, "termination-retained")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); + + assertThat( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + tenantId, instanceId)) + .isTrue(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_quarantined_actor_item_instances WHERE tenant_id = ?", + Integer.class, + tenantId)) + .isEqualTo(3); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_quarantined_actor_container_instances WHERE tenant_id = ?", + Integer.class, + tenantId)) + .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 = ?", + Integer.class, + actorId, + fixtureId(3003))) + .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, + tenantId, + instanceId)) + .isEqualTo(3); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + instanceId)) + .isEqualTo(2); + assertThat( + jdbcTemplate.queryForObject( + "SELECT sum(quantity) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + instanceId)) + .isEqualTo(17); + assertThat( + jdbcTemplate.queryForObject( + "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + instanceId)) + .isEqualTo(11); + assertThat( + jdbcTemplate.queryForObject( + "SELECT correlation_key FROM item_transfer_audits WHERE id = ?", + String.class, + fixtureId(3401))) + .isEqualTo("corr-retained"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = ?", + String.class, + fixtureId(3501))) + .isEqualTo("aabb"); + } + + @Test + void destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows() { + String auditOnlyInstance = instanceId + "-AUDIT-ONLY"; + long quarantinedActorId = + insertActor( + "legacy audit destination", + UUID.randomUUID(), + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId); + 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 (" + + fixtureId(3601) + + ", ?, " + + fixtureId(3001) + + ", 1, 'TAKE', 'effect-audit-only-quarantined', 'corr-audit-only-quarantined', 'ROOM', ?, 'CHARACTER', ?, ?)", + tenantId, + auditOnlyInstance, + quarantinedActorId, + auditOnlyInstance); + + assertNoRuntimeRowsForInstance(auditOnlyInstance); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE id = ? AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", + Integer.class, + fixtureId(3601), + quarantinedActorId)) + .isEqualTo(1); + assertThat( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + tenantId, auditOnlyInstance)) + .isTrue(); + assertThatThrownBy( + () -> + runtimeInstanceCleanupService.cleanupRuntimeInstance( + tenantId, 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 = ? AND tenant_id = ? AND correlation_key = 'corr-audit-only-quarantined' AND destination_character_id = ?", + Integer.class, + fixtureId(3601), + tenantId, + quarantinedActorId)) + .isEqualTo(1); + assertNoRuntimeRowsForInstance(auditOnlyInstance); + } + + @Test + void destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows() { + String auditOnlyInstance = instanceId + "-AUDIT-OWNER-RESOLVED"; + UUID ownerResolvedActorUuid = UUID.randomUUID(); + insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + long ownerResolvedActorId = + insertActor( + "owner-resolved audit destination fixture", + ownerResolvedActorUuid, + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + 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 (" + + fixtureId(3602) + + ", ?, " + + fixtureId(3001) + + ", 1, 'TAKE', 'effect-audit-only-owner-resolved', 'corr-audit-only-owner-resolved', 'ROOM', ?, 'CHARACTER', ?, ?)", + tenantId, + auditOnlyInstance, + ownerResolvedActorId, + auditOnlyInstance); + + assertNoRuntimeRowsForInstance(auditOnlyInstance); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE id = ? AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", + Integer.class, + fixtureId(3602), + ownerResolvedActorId)) + .isEqualTo(1); + assertThat( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + tenantId, auditOnlyInstance)) + .isFalse(); + var result = + runtimeInstanceCleanupService.cleanupRuntimeInstance( + tenantId, 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 = ? AND tenant_id = ? AND correlation_key = 'corr-audit-only-owner-resolved' AND destination_character_id = ?", + Integer.class, + fixtureId(3602), + tenantId, + 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, + tenantId, + gameInstanceId)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + gameInstanceId)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + gameInstanceId)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + gameInstanceId)) + .isZero(); + } + + @Test + void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { + insertActor( + "legacy shared actor", + UUID.randomUUID(), + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId); + jdbcTemplate.update( + "INSERT INTO items (id, name, tenant_id, is_container) VALUES (" + + fixtureId(3901) + + ", 'Unresolved ground item', ?, false)", + tenantId); + jdbcTemplate.update( + "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " + + "VALUES (?, ?, 'room-unresolved', " + + fixtureId(3901) + + ", 2, 1)", + tenantId, + instanceId); + + assertThat( + quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( + tenantId, instanceId)) + .isTrue(); + assertThatThrownBy( + () -> + runtimeInstanceCleanupService.cleanupRuntimeInstance( + tenantId, instanceId, "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, + tenantId, + instanceId)) + .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.randomUUID(); + insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + long actorId = + insertActor( + "Tenant-owned actor", + characterUuid, + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + + Character crossTenantUpdate = + characterRepository.findByIdAndTenantId(actorId, tenantId).orElseThrow(); + int originalVersion = crossTenantUpdate.getVersion(); + int originalExperience = crossTenantUpdate.getExperience(); + crossTenantUpdate.setTenantId(tenantId + 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, tenantId).orElseThrow(); + assertThat(unchanged.getTenantId()).isEqualTo(tenantId); + assertThat(unchanged.getName()).isEqualTo("Tenant-owned actor"); + assertThat(unchanged.getExperience()).isEqualTo(originalExperience); + assertThat(unchanged.getVersion()).isEqualTo(originalVersion); + + Character validUpdate = + characterRepository.findByIdAndTenantId(actorId, tenantId).orElseThrow(); + validUpdate.setName("Tenant-owned actor updated"); + Character saved = characterRepository.save(validUpdate); + assertThat(saved.getTenantId()).isEqualTo(tenantId); + assertThat(saved.getName()).isEqualTo("Tenant-owned actor updated"); + assertThat(saved.getVersion()).isEqualTo(originalVersion + 1); + } + + private Map inventoryHolderMutationCounts(long characterId) { + return Map.of( + "item_instances", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_instances WHERE tenant_id = ?", Integer.class, tenantId), + "container_instances", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM container_instances WHERE tenant_id = ?", + Integer.class, + tenantId), + "item_stacks", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_stacks WHERE tenant_id = ?", Integer.class, tenantId), + "inventory", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM inventory WHERE character_id = ?", Integer.class, characterId), + "room_ground_inventory", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", + Integer.class, + tenantId, + instanceId), + "item_transfer_audits", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM item_transfer_audits WHERE tenant_id = ?", + Integer.class, + tenantId), + "entity_mutation_effects", + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_mutation_effects WHERE tenant_id = ?", + Integer.class, + tenantId)); + } + + 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, + tenantId, + 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 new file mode 100644 index 0000000000..6f3995a989 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java @@ -0,0 +1,57 @@ +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 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/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/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; + } +} 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/ScopedCharacterResolverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java new file mode 100644 index 0000000000..3ecafd1c27 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import 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)); + + 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"); + verifyNoInteractions(repository); + } +} 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); 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); + } + } +} 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 e9aba2412f5a8918cc26721ff10d2b071f2e08b0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:50:10 +1300 Subject: [PATCH 02/28] docs(entity): qualify current-parent identity stage proof --- .../microservices/entity-management-service/README.md | 2 +- .../entity-management-service/runtime-and-data.md | 6 +++--- .../gameplay-rules-entities-and-effects.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index 6f3989b11b..fe365448ca 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Persisted rows and realm-aware listing code exist. V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Unit and fixture proof limits, including the absence of physical PostgreSQL and authenticated Game Session-to-Entity network proof, are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). +Persisted rows and realm-aware listing code exist. V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Stage 1 validation and remaining proof gaps are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). 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. 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 8932fc1501..edfb5030d5 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,11 +13,11 @@ 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, production, and test 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 historical full-source integration evidence and remaining gaps; this Stage 1 split has not been validated. +- Entity's standard, production, and test 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 Stage 1 validation results 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 persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Current execution and proof status is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); physical PostgreSQL and authenticated Game Session-to-Entity mTLS/network proof are not claimed. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. -- Legacy character roster/name lookup paths 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. The original full-source container-location fixture and conditional service tests use explicitly mocked test guards; this Stage 1 split has no integration proof for those downstream paths and does not establish owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. +- Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. See [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for proof status and remaining gaps. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. +- Legacy character roster/name lookup paths 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. The Stage 1 PostgreSQL integration cases use test-only mocked guards and prove only the bounded persistence and denial scenarios recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); they do not establish 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. - 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. 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 a722fafc45..cbd7474f29 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 @@ -28,8 +28,8 @@ 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 is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `partial` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. Historical full-source e3 evidence records a local combined Entity run with 291 passing unit tests and an exact-head [hosted Entity integration-test job](https://github.com/benhook1013/FireMUD/actions/runs/37868666749/job/113621467457); the log records actual `:entity-management-service:integrationTest` execution and `BUILD SUCCESSFUL` in 5m49, with no executed-case count artifact. That full-source run also includes PostgreSQL-backed receiver integration proof, but none of it is exact-head proof for this split postimage. Split-specific compilation/tests, authenticated Game Session-to-Entity mTLS/network proof, and live PLAY proof are unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | -| 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` 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 bypasses the Entity replay ledger. | `partial` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. This split has not been validated. | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `partial` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | +| 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` 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 bypasses the Entity replay ledger. | `partial` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. Stage 1 validation and proof status are recorded under [GR-3.1](./gameplay-rules-entities-and-effects.md#capability-status). | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, 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 code exists, but production actor-scoped equipment admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment service/controller and item-command tests cover slot compatibility and binding, not production owner-qualified actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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. Owner-qualified runtime admission, 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 the self-targeted `APPLY_ACTION_STATE` command path exist, but scoped Entity actor-state/effect access 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; receiver test execution and proof status are recorded under GR-3.1. | [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 owner-qualified 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. | From c42e434e654a845f4d73bc623670b1688cb54401 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:06:00 +1300 Subject: [PATCH 03/28] docs(entity): use supported bounded verification states --- .../gameplay-rules-entities-and-effects.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 cbd7474f29..0759457c7e 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 @@ -28,8 +28,8 @@ 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 is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `partial` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | -| 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` 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 bypasses the Entity replay ledger. | `partial` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. Stage 1 validation and proof status are recorded under [GR-3.1](./gameplay-rules-entities-and-effects.md#capability-status). | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `proven` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | +| 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` 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 bypasses the Entity replay ledger. | `audited` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. Stage 1 validation and proof status are recorded under [GR-3.1](./gameplay-rules-entities-and-effects.md#capability-status). | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, 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 code exists, but production actor-scoped equipment admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment service/controller and item-command tests cover slot compatibility and binding, not production owner-qualified actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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. Owner-qualified runtime admission, 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 the self-targeted `APPLY_ACTION_STATE` command path exist, but scoped Entity actor-state/effect access 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; receiver test execution and proof status are recorded under GR-3.1. | [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 owner-qualified 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. | From 0de577e6befbd2b79637d1640777f186b6c93789 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:53:19 +1300 Subject: [PATCH 04/28] Qualify retained actor identity guards and cleanup hold errors --- .../api-contracts.md | 1 + .../entity-management-service/operations.md | 2 +- .../runtime-and-data.md | 2 +- .../ActorActiveConditionRepository.java | 55 ++++++------- .../ActorResourceStateRepository.java | 41 +++------- .../CharacterEquipmentRepository.java | 9 ++- .../repository/CharacterFriendRepository.java | 13 +++- .../repository/CharacterRepository.java | 42 +++++++--- ...JooqEntityManagementRepositorySupport.java | 38 +++++++++ .../RuntimeInstanceCleanupHeldException.java | 7 ++ .../impl/EntityManagementGrpcService.java | 9 +++ .../RuntimeInstanceCleanupServiceImpl.java | 3 +- .../RetainedActorIdentityIntegrationTest.java | 6 +- .../impl/EntityManagementGrpcServiceTest.java | 78 +++++++++++++++++++ ...RuntimeInstanceCleanupServiceImplTest.java | 3 +- 15 files changed, 225 insertions(+), 84 deletions(-) create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index bf12d23d73..7effc35938 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -43,6 +43,7 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. +- `CleanupRuntimeInstance(CleanupRuntimeInstanceRequest) returns (CleanupRuntimeInstanceResponse)` – validates the tenant, runtime instance and termination request identity before observing retained evidence. Unclassified runtime rows or quarantined actor audit evidence hold cleanup with application error `FAILED_PRECONDITION` and diagnostic `ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP`; this is a response-level `ErrorDetail`, not a transport gRPC status. Invalid arguments return `INVALID_ARGUMENT`, and unexpected failures remain `INTERNAL`. An observed empty target returns zero deletion counts; it does not authorize deletion of any nonempty family or establish disposal eligibility. World propagates the application error without converting a hold into successful termination. See [Runtime and Data](./runtime-and-data.md#implementation-status) for the owner classification and cleanup limits. - `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; its scope string is exactly `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and exact roster snapshot. The selection response echoes discovery bindings only; it mints no assignment receipt or admission proof, which remain with the owning downstream write/readback. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index af6540016a..76636b7103 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -88,7 +88,7 @@ Replacement operations use the stable `playableStateNamespaceId` and owner-resol - `liveness` is process-local only. - `readiness` is truthful local readiness for the currently implemented entity-query slice and must fail when the service cannot safely answer room/entity lookup traffic with its required local persistence/cache/bootstrap state. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. -- `entity.actor-condition.expiry-interval-seconds` controls the scheduled actor-condition expiry sweep. The default is 30 seconds, and the sweep globally and without a batch bound deletes rows whose `expires_at` has elapsed. Gameplay reads filter those rows before evaluating state, so an expired effect is not restored. The sweep targets only `actor_active_conditions`; separate `entity_mutation_effects` receipts remain and are checked by `ApplyActorCondition` before mutation, but a receipt-retention guarantee across the replay/restore horizon is unproved. No concrete duplicate-application or S2-loss claim is made. Target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, a safe watermark, and typed target, request-digest, and concurrency enforcement; expiry is not itself a retention or disposal decision. +- `entity.actor-condition.expiry-interval-seconds` controls the scheduled actor-condition expiry sweep. The default is 30 seconds, and the sweep globally and without a batch bound deletes rows whose `expires_at` has elapsed and whose character is `OWNER_RESOLVED`; elapsed conditions on `QUARANTINED` actors are retained. Gameplay reads filter those rows before evaluating state, so an expired effect is not restored. The sweep targets only `actor_active_conditions`; separate `entity_mutation_effects` receipts remain and are checked by `ApplyActorCondition` before mutation, but a receipt-retention guarantee across the replay/restore horizon is unproved. No concrete duplicate-application or S2-loss claim is made. Target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, a safe watermark, and typed target, request-digest, and concurrency enforcement; expiry is not itself a retention or disposal decision. ## Tick Locking 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 edfb5030d5..31d8da2e67 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 - 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 persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. See [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for proof status and remaining gaps. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. -- Legacy character roster/name lookup paths 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. The Stage 1 PostgreSQL integration cases use test-only mocked guards and prove only the bounded persistence and denial scenarios recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); they do not establish owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. +- Legacy character roster/name lookup paths 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. `ContainerInstanceLocationIntegrationTest` uses a test-only mocked scope guard for holder persistence, while `RetainedActorIdentityIntegrationTest` exercises the real fail-closed resolver; both prove only the bounded persistence and denial scenarios recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); they do not establish 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. - 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. 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..62fef1910f 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,11 @@ 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( + JooqEntityManagementRepositorySupport.ownerResolvedActorExists( + dsl, + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, + ACTOR_ACTIVE_CONDITIONS.TENANT_ID)) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -62,7 +64,11 @@ 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( + JooqEntityManagementRepositorySupport.ownerResolvedActorExists( + dsl, + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, + ACTOR_ACTIVE_CONDITIONS.TENANT_ID)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) @@ -71,7 +77,8 @@ public List findActiveForCharacter( } public ActorActiveCondition save(ActorActiveCondition entity) { - requireOwnerResolvedActor(entity.getTenantId(), entity.getCharacterId()); + JooqEntityManagementRepositorySupport.requireOwnerResolvedActor( + dsl, entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_ACTIVE_CONDITIONS) @@ -111,7 +118,11 @@ public ActorActiveCondition save(ActorActiveCondition entity) { .and( ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(entity.getPlayableStateKey())) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(entity.getCharacterId())) - .and(ownerResolvedActorExists())) + .and( + JooqEntityManagementRepositorySupport.ownerResolvedActorExists( + dsl, + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, + ACTOR_ACTIVE_CONDITIONS.TENANT_ID))) .execute(); if (updatedRows != 1) { throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); @@ -127,36 +138,14 @@ public int deleteExpired(Instant now) { .EXPIRES_AT .isNotNull() .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now))) - .and(ownerResolvedActorExists())) + .and( + JooqEntityManagementRepositorySupport.ownerResolvedActorExists( + dsl, + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, + ACTOR_ACTIVE_CONDITIONS.TENANT_ID))) .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/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 7cf103b979..dbbe409d76 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 @@ -32,13 +30,16 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO .eq(tenantId) .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId)) - .and(ownerResolvedActorExists())) + .and( + JooqEntityManagementRepositorySupport.ownerResolvedActorExists( + dsl, ACTOR_RESOURCE_STATES.CHARACTER_ID, ACTOR_RESOURCE_STATES.TENANT_ID))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } public ActorResourceState save(ActorResourceState entity) { - requireOwnerResolvedActor(entity.getTenantId(), entity.getCharacterId()); + JooqEntityManagementRepositorySupport.requireOwnerResolvedActor( + dsl, entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_RESOURCE_STATES) @@ -74,7 +75,11 @@ public ActorResourceState save(ActorResourceState entity) { .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())) + .and( + JooqEntityManagementRepositorySupport.ownerResolvedActorExists( + dsl, + ACTOR_RESOURCE_STATES.CHARACTER_ID, + ACTOR_RESOURCE_STATES.TENANT_ID))) .execute(); if (updatedRows != 1) { throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); @@ -83,32 +88,6 @@ 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 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..e8a0490329 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 @@ -5,6 +5,7 @@ import static net.firedevops.firemud.entitymanagement.jooq.Tables.ITEMS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.CharacterEquipmentEntry; import org.jooq.DSLContext; import org.jooq.Record; @@ -36,7 +37,9 @@ public Page findByIdCharacterIdAndCharacterTenantId( .CHARACTER_ID .eq(characterId) .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name())))); var content = dsl.select( CHARACTER_EQUIPMENT.CHARACTER_ID, @@ -70,7 +73,9 @@ public Page findByIdCharacterIdAndCharacterTenantId( .CHARACTER_ID .eq(characterId) .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .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..f04b905db0 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 @@ -7,6 +7,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; import org.jooq.DSLContext; @@ -67,7 +68,9 @@ public CharacterFriend save(CharacterFriend entity) { .ID .in(entity.getId().getCharacterId(), entity.getId().getFriendId()) .and(CHARACTERS.TENANT_ID.eq(entity.getTenantId())) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))); + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))); if (ownerResolvedCount != 2) { throw new IllegalStateException("FRIEND_ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); } @@ -103,7 +106,9 @@ private org.jooq.Condition ownerResolvedPair() { .ID .eq(CHARACTER_FRIEND.CHARACTER_ID) .and(CHARACTERS.TENANT_ID.eq(CHARACTER_FRIEND.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name())))); var ownerResolvedFriend = DSL.exists( dsl.selectOne() @@ -113,7 +118,9 @@ private org.jooq.Condition ownerResolvedPair() { .ID .eq(CHARACTER_FRIEND.FRIEND_ID) .and(CHARACTERS.TENANT_ID.eq(CHARACTER_FRIEND.TENANT_ID)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED")))); + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name())))); return ownerResolvedCharacter.and(ownerResolvedFriend); } 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..40ea8dc05f 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 @@ -9,6 +9,7 @@ import java.util.LinkedHashSet; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.InventoryEntry; import net.firedevops.firemud.entitymanagement.entity.InventoryKey; @@ -34,7 +35,13 @@ 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"))) + .where( + CHARACTERS + .ID + .eq(id) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .fetchOne(this::toEntity); if (character == null) { return Optional.empty(); @@ -69,7 +76,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"))) + .where( + CHARACTERS + .ID + .eq(id) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .fetchOne(this::toEntity)); } @@ -81,7 +94,9 @@ public Optional findByIdAndTenantId(Long id, Long tenantId) { .ID .eq(id) .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .fetchOne(this::toEntity)); } @@ -95,7 +110,9 @@ public Optional findByIdAndTenantIdAndPlayableStateKey( .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.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .fetchOne(this::toEntity)); } @@ -107,7 +124,7 @@ public Page findByTenantIdAndAccountIdAndPlayableStateKey( .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.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.OWNER_RESOLVED.name())); long total = dsl.fetchCount(CHARACTERS, condition); var content = dsl.selectFrom(CHARACTERS) @@ -131,7 +148,9 @@ public Optional findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( .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( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .limit(1) .fetchOne(this::toEntity)); } @@ -143,7 +162,10 @@ public long countByTenantId(Long tenantId) { public long countQuarantinedByTenantId(Long tenantId) { return dsl.fetchCount( CHARACTERS, - CHARACTERS.TENANT_ID.eq(tenantId).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("QUARANTINED"))); + CHARACTERS + .TENANT_ID + .eq(tenantId) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.QUARANTINED.name()))); } public Character save(Character entity) { @@ -152,7 +174,7 @@ public Character save(Character entity) { Long id = dsl.insertInto(CHARACTERS) .set(CHARACTERS.CHARACTER_UUID, characterUuid) - .set(CHARACTERS.ACTOR_IDENTITY_STATUS, "QUARANTINED") + .set(CHARACTERS.ACTOR_IDENTITY_STATUS, ActorIdentityStatus.QUARANTINED.name()) .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, "OWNER_PROVENANCE_MISSING") .set(CHARACTERS.TENANT_ID, entity.getTenantId()) .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) @@ -195,7 +217,9 @@ public Character save(Character entity) { .ID .eq(entity.getId()) .and(CHARACTERS.TENANT_ID.eq(entity.getTenantId())) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("OWNER_RESOLVED"))) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) .execute(); if (updatedRows != 1) { throw new IllegalStateException("CHARACTER_IDENTITY_NOT_OWNER_RESOLVED"); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java index 9a780b595c..e094c0f26f 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java @@ -1,7 +1,10 @@ package net.firedevops.firemud.entitymanagement.repository; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; + import java.util.List; import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.CharacterEquipmentEntry; import net.firedevops.firemud.entitymanagement.entity.CharacterEquipmentKey; @@ -14,6 +17,10 @@ import net.firedevops.firemud.entitymanagement.entity.ItemStackCompatibilityMode; import net.firedevops.firemud.entitymanagement.entity.RoomGroundInventoryEntry; import net.firedevops.firemud.entitymanagement.entity.RoomGroundInventoryKey; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; @@ -21,6 +28,37 @@ final class JooqEntityManagementRepositorySupport { private JooqEntityManagementRepositorySupport() {} + static Condition ownerResolvedActorExists( + DSLContext dsl, Field characterField, Field tenantField) { + return DSL.exists( + dsl.selectOne() + .from(CHARACTERS) + .where( + CHARACTERS + .ID + .eq(characterField) + .and(CHARACTERS.TENANT_ID.eq(tenantField)) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name())))); + } + + static void requireOwnerResolvedActor(DSLContext dsl, 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( + ActorIdentityStatus.OWNER_RESOLVED.name()))); + if (ownerResolvedCount != 1) { + throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); + } + } + static Page page(List content, Pageable pageable, long total) { if (pageable == null || pageable.isUnpaged()) { return new PageImpl<>(content); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java new file mode 100644 index 0000000000..f332900029 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.entitymanagement.service; + +public final class RuntimeInstanceCleanupHeldException extends IllegalStateException { + public RuntimeInstanceCleanupHeldException(String message) { + super(message); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java index 1e7e410c59..836969a212 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.entitymanagement.service.InventoryService; import net.firedevops.firemud.entitymanagement.service.PingService; import net.firedevops.firemud.entitymanagement.service.RoomEntityService; +import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import net.firedevops.firemud.entitymanagement.v1.ActorConditionState; import net.firedevops.firemud.entitymanagement.v1.ActorResourceValue; @@ -1827,6 +1828,14 @@ public void cleanupRuntimeInstance( .setDeletedItemStacks(result.deletedItemStacks()) .setDeletedItemInstances(result.deletedItemInstances()) .setDeletedContainerInstances(result.deletedContainerInstances()); + } catch (RuntimeInstanceCleanupHeldException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "CleanupRuntimeInstance", + "FAILED_PRECONDITION", + ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( 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..a241b35a63 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 @@ -2,6 +2,7 @@ import net.firedevops.firemud.entitymanagement.dto.RuntimeInstanceCleanupResultDto; import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; +import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -30,7 +31,7 @@ public RuntimeInstanceCleanupResultDto cleanupRuntimeInstance( } if (quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( tenantId, gameInstanceId)) { - throw new IllegalStateException( + throw new RuntimeInstanceCleanupHeldException( "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); 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 2ee426ee4f..c78e14fecc 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 @@ -26,6 +26,7 @@ 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.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.configuration.FluentConfiguration; @@ -64,11 +65,12 @@ class RetainedActorIdentityIntegrationTest { private String migrationSchema; @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = - new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index 8bf1256098..c93665f599 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -39,6 +39,7 @@ import net.firedevops.firemud.entitymanagement.service.InventoryService; import net.firedevops.firemud.entitymanagement.service.PingService; import net.firedevops.firemud.entitymanagement.service.RoomEntityService; +import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionRequest; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionResponse; @@ -1719,6 +1720,83 @@ public void onCompleted() {} verifyNoInteractions(runtimeInstanceCleanupService); } + @Test + void cleanupRuntimeInstanceReturnsFailedPreconditionForKnownCleanupHold() { + RuntimeInstanceCleanupService cleanupService = + Mockito.mock(RuntimeInstanceCleanupService.class); + String holdMessage = "ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP: held"; + Mockito.when(cleanupService.cleanupRuntimeInstance(1L, "GI-1", "term-1")) + .thenThrow(new RuntimeInstanceCleanupHeldException(holdMessage)); + + var response = invokeCleanupRuntimeInstance(cleanupService); + + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals(holdMessage, response.getError().getMessage()); + } + + @Test + void cleanupRuntimeInstanceKeepsUnexpectedFailuresInternal() { + RuntimeInstanceCleanupService cleanupService = + Mockito.mock(RuntimeInstanceCleanupService.class); + Mockito.when(cleanupService.cleanupRuntimeInstance(1L, "GI-1", "term-1")) + .thenThrow(new IllegalStateException("unexpected")); + + var response = invokeCleanupRuntimeInstance(cleanupService); + + assertEquals("INTERNAL", response.getError().getCode()); + } + + private net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse + invokeCleanupRuntimeInstance(RuntimeInstanceCleanupService cleanupService) { + SessionContext.setContext( + "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); + try { + EntityManagementGrpcService service = + new EntityManagementGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(CharacterService.class), + Mockito.mock(ActorStateService.class), + Mockito.mock(ActorConditionMutationService.class), + Mockito.mock(EntityDraftDesignDigestService.class), + Mockito.mock(EquipmentService.class), + Mockito.mock(InventoryService.class), + Mockito.mock(ContainerService.class), + Mockito.mock(RoomEntityService.class), + cleanupService, + effectReplayService(), + Mockito.mock(EntityUpgradeValidationService.class), + Mockito.mock(EntityTemplateReferenceService.class), + attestationService(), + new SimpleMeterRegistry(), + new EffectPayloadParser(new ObjectMapper()), + TEST_NAMESPACE); + AtomicReference + ref = new AtomicReference<>(); + service.cleanupRuntimeInstance( + net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("GI-1") + .setTerminationRequestId("term-1") + .build(), + new StreamObserver<>() { + @Override + public void onNext( + net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + return ref.get(); + } finally { + SessionContext.clear(); + } + } + @Test void autowiredConstructorDelegatesCleanupToInjectedRuntimeService() { RuntimeInstanceCleanupService runtimeInstanceCleanupService = 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 index 6f1cba49c5..1cc27334b6 100644 --- 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 @@ -5,6 +5,7 @@ import static org.mockito.Mockito.when; import net.firedevops.firemud.entitymanagement.repository.QuarantinedActorRetentionRepository; +import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -43,7 +44,7 @@ void unclassifiedOrQuarantinedEvidenceDeniesCleanupWithoutMutation() { dependencies .service() .cleanupRuntimeInstance(TENANT_ID, GAME_INSTANCE_ID, TERMINATION_REQUEST_ID)) - .isInstanceOf(IllegalStateException.class) + .isInstanceOf(RuntimeInstanceCleanupHeldException.class) .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); } From e573002e2f66f98aeb90fbca135388e10b43c9d5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:32:45 +1300 Subject: [PATCH 05/28] Order retained identity migrations after applied Saga history and prove default upgrades --- .../entity-management-service/README.md | 2 +- .../runtime-and-data.md | 4 +- .../gameplay-rules-entities-and-effects.md | 2 +- ..._quarantine_unresolved_actor_identity.sql} | 0 ...d_actor_identity_indexes_concurrently.sql} | 0 ...or_identity_indexes_concurrently.sql.conf} | 0 ...__validate_actor_identity_constraints.sql} | 0 .../RetainedActorIdentityIntegrationTest.java | 127 ++++++++++++++++-- ...FlywayPostgresqlLockConfigurationTest.java | 3 +- 9 files changed, 119 insertions(+), 19 deletions(-) rename services/entity-management-service/src/main/resources/db/migration/{V2__quarantine_unresolved_actor_identity.sql => V1003__quarantine_unresolved_actor_identity.sql} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V3__build_actor_identity_indexes_concurrently.sql => V1004__build_actor_identity_indexes_concurrently.sql} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V3__build_actor_identity_indexes_concurrently.sql.conf => V1004__build_actor_identity_indexes_concurrently.sql.conf} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V4__validate_actor_identity_constraints.sql => V1005__validate_actor_identity_constraints.sql} (100%) diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index fe365448ca..9c4ec08c02 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Persisted rows and realm-aware listing code exist. V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Stage 1 validation and remaining proof gaps are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). +Persisted rows and realm-aware listing code exist. V1003 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Stage 1 validation and remaining proof gaps are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). 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. 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 31d8da2e67..59be0f0d04 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,10 +13,10 @@ 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, production, and test 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 Stage 1 validation results and remaining gaps. +- Entity's standard, production, and test Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V1004'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 Stage 1 validation results 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 persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. See [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for proof status and remaining gaps. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. +- Entity V1003 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. See [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for proof status and remaining gaps. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. - Legacy character roster/name lookup paths 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. `ContainerInstanceLocationIntegrationTest` uses a test-only mocked scope guard for holder persistence, while `RetainedActorIdentityIntegrationTest` exercises the real fail-closed resolver; both prove only the bounded persistence and denial scenarios recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); they do not establish 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. - 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. 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 0759457c7e..438d1c25af 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 @@ -28,7 +28,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 is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `proven` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity is the target persistence authority for actor identity. V1003 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `proven` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is1005 with no out-of-order migrations. The211unit cases retain the preceding executed-run attribution and were up-to-date in the final50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V1003 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1004 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql); [V1005 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | | 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` 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 bypasses the Entity replay ledger. | `audited` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. Stage 1 validation and proof status are recorded under [GR-3.1](./gameplay-rules-entities-and-effects.md#capability-status). | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, 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 code exists, but production actor-scoped equipment admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment service/controller and item-command tests cover slot compatibility and binding, not production owner-qualified actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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. Owner-qualified runtime admission, 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 the self-targeted `APPLY_ACTION_STATE` command path exist, but scoped Entity actor-state/effect access 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; receiver test execution and proof status are recorded under GR-3.1. | [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 owner-qualified 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/db/migration/V2__quarantine_unresolved_actor_identity.sql b/services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql rename to services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql 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/V1004__build_actor_identity_indexes_concurrently.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql rename to services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql 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/V1004__build_actor_identity_indexes_concurrently.sql.conf similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql.conf rename to services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql.conf 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/V1005__validate_actor_identity_constraints.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql rename to services/entity-management-service/src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql 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 c78e14fecc..58096b6170 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,6 +7,8 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -28,6 +30,7 @@ import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationState; import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; @@ -62,7 +65,7 @@ class RetainedActorIdentityIntegrationTest { private UUID accountUuid; private UUID namespaceUuid; private long fixtureIdOffset; - private String migrationSchema; + private String testServiceSchema; @Container static PostgreSQLContainer postgres = @@ -76,6 +79,8 @@ class RetainedActorIdentityIntegrationTest { static void configure(DynamicPropertyRegistry registry) { PostgresBackedServiceTestSupport.registerPostgresService( registry, postgres, "entity_management_service"); + registry.add( + "spring.flyway.locations", () -> "classpath:db/migration,classpath:db/migration/saga"); PostgresBackedServiceTestSupport.registerRedisService(registry, redis); } @@ -89,6 +94,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private ScopedCharacterResolver scopedCharacterResolver; @Autowired private CharacterService characterService; @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private Flyway flyway; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @@ -111,8 +117,9 @@ private long fixtureIdOffset(String testMethodName) { case "destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows" -> 400_000L; case "destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows" -> 500_000L; case "unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping" -> 600_000L; - case "flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints" -> 700_000L; + case "flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints" -> 700_000L; case "characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch" -> 800_000L; + case "freshDefaultFlywayInstallsCompleteCombinedManifest" -> 900_000L; default -> throw new IllegalArgumentException("No fixture ID range for " + testMethodName); }; } @@ -816,10 +823,47 @@ void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { .isEqualTo(2); } + @Test + void freshDefaultFlywayInstallsCompleteCombinedManifest() { + // Flyway normalizes the declared Saga sub-location into its recursive parent location. + assertThat(flyway.getConfiguration().getLocations()) + .extracting(location -> location.getDescriptor()) + .containsExactly("classpath:db/migration"); + assertThat(flyway.getConfiguration().getTable()) + .isEqualTo("flyway_schema_history_entity_management_service"); + assertThat(flyway.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(flyway.info().applied()) + .filteredOn(migration -> migration.getVersion() != null) + .extracting(migration -> migration.getVersion().getVersion()) + .containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005"); + assertThat(flyway.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1005")); + assertThat(flyway.info().applied()) + .extracting(migration -> migration.getState()) + .doesNotContain(MigrationState.OUT_OF_ORDER); + } + @Test @Timeout(value = 3, unit = TimeUnit.MINUTES) - void flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLException { - migrateLegacySchemaToV1(); + void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLException { + migrateLegacySchemaToParentFrontier(); + List parentHistory = readMigrationHistory(); + assertThat(parentHistory) + .extracting(MigrationHistoryEntry::version) + .containsExactly("1", "1000", "1001", "1002"); + assertThat(parentHistory) + .extracting(MigrationHistoryEntry::script) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql"); + assertThat(parentHistory) + .allSatisfy( + entry -> { + assertThat(entry.success()).isTrue(); + assertThat(entry.checksum()).isNotNull(); + }); try (Connection connection = connectToMigrationSchema()) { var statement = connection.createStatement(); statement.executeUpdate( @@ -859,6 +903,24 @@ void flywayV1ToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLExcept migrateLegacySchemaToLatest(); + List upgradedHistory = readMigrationHistory(); + assertThat(upgradedHistory.subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + assertThat(upgradedHistory) + .extracting(MigrationHistoryEntry::version) + .containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005"); + assertThat(upgradedHistory) + .extracting(MigrationHistoryEntry::script) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql", + "V1003__quarantine_unresolved_actor_identity.sql", + "V1004__build_actor_identity_indexes_concurrently.sql", + "V1005__validate_actor_identity_constraints.sql"); + assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); + try (Connection connection = connectToMigrationSchema(); var statement = connection.createStatement()) { assertThat( @@ -1199,29 +1261,41 @@ private void insertItemInstance( visibleRef); } - private void migrateLegacySchemaToV1() throws SQLException { - migrationSchema = "retained_actor_v1_to_v2_" + UUID.randomUUID().toString().replace("-", ""); + private void migrateLegacySchemaToParentFrontier() throws SQLException { + testServiceSchema = "rai_" + UUID.randomUUID().toString().replace("-", ""); try (Connection connection = DriverManager.getConnection( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); var statement = connection.createStatement()) { - statement.execute("CREATE SCHEMA " + migrationSchema); + statement.execute("CREATE SCHEMA " + testServiceSchema); } - migrationFlyway().target(MigrationVersion.fromVersion("1")).load().migrate(); + Flyway parentFlyway = migrationFlyway().target(MigrationVersion.fromVersion("1002")).load(); + assertThat(parentFlyway.getConfiguration().isOutOfOrder()).isFalse(); + parentFlyway.migrate(); + assertThat(parentFlyway.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1002")); } private void migrateLegacySchemaToLatest() { - migrationFlyway().load().migrate(); + Flyway upgradeFlyway = migrationFlyway().load(); + assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); + upgradeFlyway.migrate(); + assertThat(upgradeFlyway.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1005")); + assertThat(upgradeFlyway.info().applied()) + .extracting(migration -> migration.getState()) + .doesNotContain(MigrationState.OUT_OF_ORDER); } 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)); + .schemas(testServiceSchema) + .defaultSchema(testServiceSchema) + .table("flyway_schema_history_" + testServiceSchema) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", testServiceSchema)); configuration .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); @@ -1234,11 +1308,36 @@ private Connection connectToMigrationSchema() throws SQLException { DriverManager.getConnection( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); try (var statement = connection.createStatement()) { - statement.execute("SET search_path TO " + migrationSchema); + statement.execute("SET search_path TO " + testServiceSchema); } return connection; } + private List readMigrationHistory() throws SQLException { + List history = new ArrayList<>(); + try (Connection connection = connectToMigrationSchema(); + var statement = connection.createStatement(); + var rows = + statement.executeQuery( + "SELECT installed_rank, version, script, checksum, success FROM flyway_schema_history_" + + testServiceSchema + + " WHERE version IS NOT NULL ORDER BY installed_rank")) { + while (rows.next()) { + history.add( + new MigrationHistoryEntry( + rows.getInt("installed_rank"), + rows.getString("version"), + rows.getString("script"), + rows.getObject("checksum", Integer.class), + rows.getBoolean("success"))); + } + } + return history; + } + + private record MigrationHistoryEntry( + int installedRank, String version, String script, Integer checksum, boolean success) {} + private long readLong(java.sql.Statement statement, String sql) throws SQLException { try (var rows = statement.executeQuery(sql)) { assertThat(rows.next()).isTrue(); 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 6f3995a989..b83ab5338e 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 @@ -18,7 +18,8 @@ class FlywayPostgresqlLockConfigurationTest { void identityValidationScansFinishBeforeStrongLockFinalization() throws IOException { String migration = Files.readString( - Path.of("src/main/resources/db/migration/V4__validate_actor_identity_constraints.sql")); + Path.of( + "src/main/resources/db/migration/V1005__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"); From d5f7d09e6b28acb511b58a200a8bcdefd77c7c9c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:15:40 +1300 Subject: [PATCH 06/28] Prepare passive Entity and Account storage while preserving existing gameplay --- .github/workflows/ci.yml | 4 + build.gradle.kts | 8 +- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 10 + .../entity-management-service/README.md | 2 +- .../api-contracts.md | 8 +- .../entity-management-service/operations.md | 18 +- .../runtime-and-data.md | 29 +- ...system-architecture-database-migrations.md | 2 +- .../gameplay-rules-entities-and-effects.md | 16 +- .../player-access-and-session.md | 6 + dev-tools/validation/check-flyway-versions.py | 383 +++-- ...ginal_start_session_source_protections.sql | 1460 +++++++++++++++++ ...tionProtectionPostgresIntegrationTest.java | 1041 ++++++++++++ ...sionProtectionPostgresIntegrationTest.java | 1442 ++++++++++++++++ .../ActorActiveConditionRepository.java | 59 +- .../ActorResourceStateRepository.java | 42 +- .../CharacterEquipmentRepository.java | 11 +- .../repository/CharacterFriendRepository.java | 59 +- .../repository/CharacterRepository.java | 1200 +++++++++++++- ...JooqEntityManagementRepositorySupport.java | 38 - .../QuarantinedActorRetentionRepository.java | 90 - .../service/CanonicalGameplayRosterActor.java | 21 + .../CanonicalGameplayRosterEntryPolicy.java | 9 + ...nonicalGameplayRosterExecutionContext.java | 58 + .../CanonicalGameplayRosterOwnerEvidence.java | 19 + ...onicalGameplayRosterOwnerEvidencePort.java | 27 + .../CanonicalGameplayRosterReadRequest.java | 28 + ...ayRosterSelectedAssignmentReadRequest.java | 36 + ...playRosterSelectedAssignmentReference.java | 35 + ...meplayRosterSelectedAssignmentService.java | 117 ++ .../CanonicalGameplayRosterService.java | 54 + .../CanonicalGameplayRosterSnapshot.java | 26 + ...CanonicalGameplayRosterSnapshotDigest.java | 68 + ...onicalGameplayRosterSnapshotReference.java | 19 + .../CanonicalGameplayRosterTarget.java | 84 + .../PreseededActorAccountIdentityPort.java | 10 + ...reseededActorAssignmentExpectedTarget.java | 96 ++ ...eededActorAssignmentGrantIntentDigest.java | 56 + .../PreseededActorAssignmentIntentDigest.java | 54 + ...PreseededActorAssignmentOwnerEvidence.java | 129 ++ ...eededActorAssignmentOwnerEvidencePort.java | 35 + .../PreseededActorAssignmentReceipt.java | 92 ++ ...reseededActorAssignmentReceiptRequest.java | 31 + ...reseededActorAssignmentReceiptService.java | 20 + .../PreseededActorAssignmentRequest.java | 34 + .../PreseededActorAssignmentResult.java | 27 + .../PreseededActorAssignmentService.java | 134 ++ .../service/PreseededActorCorePayload.java | 42 + .../PreseededActorStagingEligibilityPort.java | 12 + ...seededActorAssignmentAuthorityAdapter.java | 111 ++ ...nedPreseededActorAssignmentCapability.java | 602 +++++++ .../RunOwnedPreseededAssignmentAuthority.java | 34 + .../RuntimeInstanceCleanupHeldException.java | 7 - .../service/ScopedCharacterResolver.java | 24 +- .../service/impl/CharacterServiceImpl.java | 58 +- .../impl/EntityManagementGrpcService.java | 9 - .../EntityUpgradeValidationServiceImpl.java | 13 +- .../RuntimeInstanceCleanupServiceImpl.java | 45 +- .../V1006__preseeded_actor_assignment.sql | 208 +++ ...7__preseeded_assignment_owner_snapshot.sql | 63 + ...8__canonical_gameplay_roster_snapshots.sql | 221 +++ ...onical_publication_uuid_actor_evidence.sql | 162 ++ ...V1010__canonical_roster_owner_counters.sql | 108 ++ ...anonicalGameplayRosterIntegrationTest.java | 431 +++++ ...tainerInstanceLocationIntegrationTest.java | 52 +- ...eseededActorAssignmentIntegrationTest.java | 1168 +++++++++++++ .../RetainedActorIdentityIntegrationTest.java | 889 ++-------- .../ActorActiveConditionRepositoryTest.java | 120 -- .../ActorResourceStateRepositoryTest.java | 117 -- .../CharacterFriendRepositoryTest.java | 133 -- ...arantinedActorRetentionRepositoryTest.java | 89 - ...ayRosterSelectedAssignmentServiceTest.java | 481 ++++++ .../CanonicalGameplayRosterServiceTest.java | 318 ++++ .../PreseededActorAssignmentServiceTest.java | 682 ++++++++ .../PreseededActorCorePayloadTest.java | 51 + ...edActorAssignmentAuthorityAdapterTest.java | 428 +++++ ...reseededActorAssignmentCapabilityTest.java | 353 ++++ .../service/ScopedCharacterResolverTest.java | 46 - .../impl/CharacterServiceImplListTest.java | 46 +- .../impl/CharacterServiceImplTest.java | 45 +- .../impl/ContainerServiceImplTest.java | 47 +- .../impl/EntityManagementGrpcServiceTest.java | 78 - .../impl/EquipmentServiceImplTest.java | 49 +- .../service/impl/FriendServiceImplTest.java | 27 +- .../impl/InventoryServiceImplTest.java | 35 +- ...RuntimeInstanceCleanupServiceImplTest.java | 59 - 87 files changed, 12541 insertions(+), 2171 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java delete 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/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java delete mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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 create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.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/.github/workflows/ci.yml b/.github/workflows/ci.yml index 743a38ea83..c03ea3113e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -552,6 +552,8 @@ jobs: - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 - name: ⚙️ Set Up Java uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6 @@ -573,6 +575,8 @@ jobs: cache-read-only: false - name: 🧪 Check Flyway Migration Versions + env: + FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} run: ./gradlew checkFlywayVersions grpc-transport-config-sanity-checks: diff --git a/build.gradle.kts b/build.gradle.kts index a09a2c7b6c..13ca387277 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -411,8 +411,12 @@ tasks.register("linkCheck") { tasks.register("checkFlywayVersions") { group = "verification" - description = "Checks service Flyway migrations for duplicate or out-of-order versions." - commandLine("bash", "dev-tools/validation/check-flyway-versions.sh") + description = "Checks combined Flyway migration versions and additions against an immutable parent when available." + val baseRef = providers.gradleProperty("flywayBaseRef").orNull + commandLine( + listOf("bash", "dev-tools/validation/check-flyway-versions.sh") + + if (baseRef != null) listOf("--base-ref", baseRef) else emptyList() + ) } tasks.register("checkGrpcTransportConfig") { diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fe7306cdbf..3610bd373d 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. + The initial private gameplay LOGIN owner, signer, registry, and response-recovery code is present as unregistered Account source, with focused proof sources. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. This does not add or activate an API, proto method, or Spring composition; the source has no caller-selected profile or property override. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact proof scope; deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, and runtime activation remain unproved. Account UUID generation currently has three established provenances: `ACCOUNT_REPOSITORY_INSERT` uses `AccountRepository` and `UUID.randomUUID()`; `ACCOUNT_V29_MIGRATION` uses `gen_random_uuid()` for retained rows; and `ACCOUNT_DATABASE_INSERT` uses the `gen_random_uuid()` database default. These current producer outputs are RFC 4122 version 4 UUIDs. This records generator provenance and does not claim that database constraints reject custom UUID versions. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fa969a4388..a11206fa36 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). + Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). @@ -329,3 +331,11 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b This service sends verification and password reset emails using a configured SMTP provider. 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 a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. + +## Original StartSession Source-Protection Storage + +Account retains admission and activation protection separately from the original World participation. Each protection stores the complete original tuple and redemption projection, capture, ordered source-child evidence, actual Game Session owner mutation/attempt/fence, and unchanged original lease expiry. Admission additionally binds the complete World admission hold; activation binds the canonical World PREPARING evidence and its separate activation request. Database checks validate the nested original issuance-operation identity rather than accepting a matching projection hash alone. Identity/fence allocation, exact current lookup and append-only guards preserve the first protection without renewing authority. + +The existing Account source-lock order remains canonical: source-key locks precede protection-row locks, and NOWAIT refuses a reversed or unavailable acquisition. Pending admission or activation blocks the existing source-hold, source-change and hosted-terms disclosure paths until the distinct protection has its exact immutable terminal settlement. Expiry, World receiving settlement, absence and an asserted outcome cannot release another protection. Settlement stores the complete original protection and exact terminal binding; these SQL checks validate integrity and do not authenticate the terminal producer. The owner obligations remain defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). + +V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index 9c4ec08c02..6cf82e0421 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Persisted rows and realm-aware listing code exist. V1003 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Stage 1 validation and remaining proof gaps are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). +Entity V1003–V1010 prepares opaque actor UUIDs, quarantine metadata, namespace/scope integrity, and assignment/receipt/roster storage while retaining legacy values. Manually composed source services and exact canonical repository readers are present without Spring registration, authenticated clients, or gRPC handlers. Existing legacy reads, roster listing, updates, cache access, scoped consumers, condition expiry, and cleanup retain develop behavior; this preparation does not enforce runtime quarantine or replace gameplay admission. Authenticated owner provenance, the real Game Session caller and execution replacement, and production activation remain unproved. Current boundary proof is pending under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); [Entity API Contracts](./api-contracts.md#implementation-status) owns the detailed source and wire contract. 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. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 7effc35938..a6e0470431 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,9 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; proof of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, remains pending under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. + +The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. @@ -43,8 +45,8 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. -- `CleanupRuntimeInstance(CleanupRuntimeInstanceRequest) returns (CleanupRuntimeInstanceResponse)` – validates the tenant, runtime instance and termination request identity before observing retained evidence. Unclassified runtime rows or quarantined actor audit evidence hold cleanup with application error `FAILED_PRECONDITION` and diagnostic `ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP`; this is a response-level `ErrorDetail`, not a transport gRPC status. Invalid arguments return `INVALID_ARGUMENT`, and unexpected failures remain `INTERNAL`. An observed empty target returns zero deletion counts; it does not authorize deletion of any nonempty family or establish disposal eligibility. World propagates the application error without converting a hold into successful termination. See [Runtime and Data](./runtime-and-data.md#implementation-status) for the owner classification and cleanup limits. -- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; its scope string is exactly `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and exact roster snapshot. The selection response echoes discovery bindings only; it mints no assignment receipt or admission proof, which remain with the owning downstream write/readback. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. + +- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – target `PRESEEDED_ONLY` pre-admission wire contract described in [Implementation Status](#implementation-status). Source models and manually composed services are present; authenticated transport handlers and caller registration are not. The result is discovery evidence, not actor admission or a session-binding shortcut. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 76636b7103..25178aa707 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -10,9 +10,11 @@ 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 +The actor-identity and assignment/roster changes in this preparation are storage and unregistered source only. Existing runtime consumers, expiry, and cleanup retain develop behavior; no new quarantine hold or authenticated roster handler is active. Follow [Entity Runtime and Data](./runtime-and-data.md#implementation-status) for this boundary and [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof) for pending proof. -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. +## V1004 Concurrent Index Migration Recovery + +Entity V1004 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: @@ -60,23 +62,23 @@ WHERE activity.datname = current_database() 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 only the statement for the specific index confirmed invalid and unattached; each statement must run outside a transaction. +An invalid index may be removed only after confirming it is one of these exact V1004 indexes, is unattached to a constraint, and its definition matches the expected V1004 object. Use the deployed schema explicitly. Run only the statement for the specific index confirmed invalid and unattached; each statement must run outside a transaction. -Only if inspection confirms `ux_characters_character_uuid_idx` is invalid, unattached, and matches the expected V3 definition: +Only if inspection confirms `ux_characters_character_uuid_idx` is invalid, unattached, and matches the expected V1004 definition: ```sql DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".ux_characters_character_uuid_idx; ``` -Only if inspection independently confirms `idx_characters_owner_resolved_roster` is invalid, unattached, and matches the expected V3 definition: +Only if inspection independently confirms `idx_characters_owner_resolved_roster` is invalid, unattached, and matches the expected V1004 definition: ```sql 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. +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 V1004 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. -Dropping invalid, unattached indexes does not remove the failed V3 entry from Flyway history. Only when exact post-cleanup inspection proves that both `ux_characters_character_uuid_idx` and `idx_characters_owner_resolved_roster` indexes and the `ux_characters_character_uuid` constraint are absent, repair the failed V3 history entry in the owning Entity schema/history table before rerunning migrate, keeping writer admission closed and writers quiesced throughout. Any surviving valid object or mixed state still requires the operator-reviewed, phase-specific roll-forward plan above. +Dropping invalid, unattached indexes does not remove the failed V1004 entry from Flyway history. Only when exact post-cleanup inspection proves that both `ux_characters_character_uuid_idx` and `idx_characters_owner_resolved_roster` indexes and the `ux_characters_character_uuid` constraint are absent, repair the failed V1004 history entry in the owning Entity schema/history table before rerunning migrate, keeping writer admission closed and writers quiesced throughout. Any surviving valid object or mixed state still requires the operator-reviewed, phase-specific roll-forward plan above. ## Target Replacement Operations @@ -88,7 +90,7 @@ Replacement operations use the stable `playableStateNamespaceId` and owner-resol - `liveness` is process-local only. - `readiness` is truthful local readiness for the currently implemented entity-query slice and must fail when the service cannot safely answer room/entity lookup traffic with its required local persistence/cache/bootstrap state. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. -- `entity.actor-condition.expiry-interval-seconds` controls the scheduled actor-condition expiry sweep. The default is 30 seconds, and the sweep globally and without a batch bound deletes rows whose `expires_at` has elapsed and whose character is `OWNER_RESOLVED`; elapsed conditions on `QUARANTINED` actors are retained. Gameplay reads filter those rows before evaluating state, so an expired effect is not restored. The sweep targets only `actor_active_conditions`; separate `entity_mutation_effects` receipts remain and are checked by `ApplyActorCondition` before mutation, but a receipt-retention guarantee across the replay/restore horizon is unproved. No concrete duplicate-application or S2-loss claim is made. Target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, a safe watermark, and typed target, request-digest, and concurrency enforcement; expiry is not itself a retention or disposal decision. +- `entity.actor-condition.expiry-interval-seconds` controls the scheduled actor-condition expiry sweep. The default is 30 seconds, and the sweep globally and without a batch bound deletes rows whose `expires_at` has elapsed. Gameplay reads filter those rows before evaluating state, so an expired effect is not restored. The sweep targets only `actor_active_conditions`; separate `entity_mutation_effects` receipts remain and are checked by `ApplyActorCondition` before mutation, but a receipt-retention guarantee across the replay/restore horizon is unproved. No concrete duplicate-application or S2-loss claim is made. Target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, a safe watermark, and typed target, request-digest, and concurrency enforcement; expiry is not itself a retention or disposal decision. ## Tick Locking 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 59be0f0d04..a774f9f19b 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -11,19 +11,21 @@ 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, production, and test Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V1004'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 Stage 1 validation results 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 V1003 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. See [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for proof status and remaining gaps. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. -- Legacy character roster/name lookup paths 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. `ContainerInstanceLocationIntegrationTest` uses a test-only mocked scope guard for holder persistence, while `RetainedActorIdentityIntegrationTest` exercises the real fail-closed resolver; both prove only the bounded persistence and denial scenarios recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); they do not establish 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. +- 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. +- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows; existing legacy consumers retain develop behavior and do not enforce that new metadata. +- Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The source services are manually composed and unregistered; no authenticated transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). +- Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. The qualified donor's historical proof does not qualify this passive recut; its full check, fresh packaged player-flow proof, and actual-parent upgrade proof remain pending under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). +- Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. + ## Architecture and Design Notes - Uses the service-owned PostgreSQL schema and the platform `jOOQ + Flyway` persistence direction. Flyway owns schema evolution and generated jOOQ types are the default SQL access path; the narrow PostgreSQL-specific plain-SQL escape hatch requires focused proof and does not create a parallel ORM authority. @@ -105,7 +107,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 +128,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 +145,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 +308,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 +422,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/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 532816116c..3267c7c701 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -47,7 +47,7 @@ This document is the current target authority for SQL persistence, schema owners - Saga tables are created inside the owning service schema via the shared `${serviceSchema}.saga_*` migrations rather than a separate dedicated `saga` schema. - New migrations are committed alongside service code so history stays with the owning service. -Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. +Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. Default Flyway ordering and validation remain enabled. Before allocating a new service-local version, inspect the immutable receiving parent’s complete effective migration set, including every shared location loaded by that service; the new version must be strictly greater than that combined local/shared frontier. A new shared migration must be strictly greater than every adopting service’s effective frontier, so a service-local extension cannot make the next shared migration an ignored lower version. Compare added artifacts against the receiving parent with the existing Flyway version checker, and prove fresh bootstrap and upgrade from the actual installed combined history. Re-version only never-applied candidate artifacts when correcting allocation; preserve their SQL bytes and every applied artifact’s filename and checksum. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. ### Objective Compatibility Gates 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 438d1c25af..f505688b3c 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 @@ -12,7 +12,7 @@ Current residual: the crafting handlers remain runtime-reachable legacy implemen The capability-table CRUD entry below refers only to this legacy persistence/service-controller seam; it is not a supported public REST API or gameplay crafting flow. -PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). Stage 1 adds Entity-owned opaque character identity, quarantine for unresolved legacy provenance, and fail-closed legacy consumers; it does not establish owner provenance, identity promotion, gameplay admission, or PLAY. PRESEEDED_ONLY assignment and owner-qualified roster/receipt source evidence remain in the following stage. Gameplay tracking retains only the consequence that actor-state/effect work must use Entity's persisted realm-valid identity; current synthetic-ID, fixed-schema, policy-resolution, provisioning, and fork-copy proof gaps remain. +PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). The preparation adds opaque UUID/quarantine metadata, canonical assignment/receipt/roster storage, and manually composed unregistered source services. Existing legacy consumers retain develop behavior. Authenticated owner provenance, real caller/controller/execution replacement, runtime quarantine enforcement, and gameplay activation remain later work; storage fixtures do not close those gaps. Passive `CHARACTER_CREATE/1` receiving support is now present in common-platform-core: [the family codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java) composes the existing `MutationDigestV1` grammar with schema-three `RealmEntryPolicy`; its bounded [authored-source projection parser](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) checks the retained `GameplayRuleManifest` and `PlayerCreationDescriptor` inputs. The [shared vector resource](../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) retains four literal positive preimages and now includes required negative cases; the [focused codec test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java) exercises the production decoder against those fixtures and checks additional source contradictions. The current local run and its limits are recorded under [Validation and Proof](#validation-and-proof). This remains local-only receiver support: it does not establish a Game Session producer, authenticated source readback, Entity terminal or owner protections, or route activation, so GR-3.1 remains partial. The [canonical family schema](../../architecture/microservices/entity-management-service/character-create-action-schema.md) owns the contract details. @@ -28,12 +28,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 is the target persistence authority for actor identity. V1003 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `proven` - Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is1005 with no out-of-order migrations. The211unit cases retain the preceding executed-run attribution and were up-to-date in the final50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. | [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); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V1003 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1004 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql); [V1005 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | -| 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` 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 bypasses the Entity replay ledger. | `audited` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. Stage 1 validation and proof status are recorded under [GR-3.1](./gameplay-rules-entities-and-effects.md#capability-status). | [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) | Blank-`effectId` replay-ledger bypass and ingress remediation remain open, alongside canonical owner-qualified admission, 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 code exists, but production actor-scoped equipment admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment service/controller and item-command tests cover slot compatibility and binding, not production owner-qualified actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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. Owner-qualified runtime admission, 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 the self-targeted `APPLY_ACTION_STATE` command path exist, but scoped Entity actor-state/effect access 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; receiver test execution and proof status are recorded under GR-3.1. | [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 owner-qualified 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` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `audited` - source and focused storage proof anchors are present, but this passive recut has no completed canonical full check, fresh packaged player-flow proof, or default combined-location/actual-parent upgrade proof. Historical donor runs do not qualify this boundary; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [Entity migrations](../../../services/entity-management-service/src/main/resources/db/migration/) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | +| 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 read code exist, but production XP/level mutation and actor-state reads remain fail-closed pending owner-qualified actor resolution; ability and skill progression is not implemented. | `audited` - focused character progression and actor-state tests cover the bounded XP/level seam with a mocked resolver; this conditional service 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 @@ -113,6 +113,10 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- Current passive Entity preparation is unvalidated: V1003–V1010 follows unchanged develop V1/Saga1000–1002, and the qualified immutable donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` preserves the complete migration/storage source. That donor qualification does not apply to this recut. Main still owns the canonical full Entity check, documentation checks, fresh-image positive `LOGIN` → `PLAY` → `LOOK`, and default combined-location plus actual-parent upgrade proof. Authenticated owner/real caller/execution replacement and production activation remain unproved; no Game Design semantic or migration-order closure is claimed here. + +- Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is1005 with no out-of-order migrations. The211unit cases retain the preceding executed-run attribution and were up-to-date in the final50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. + - The integrated passive receiver review corrections on develop `b95aade1546a1d90fde3e884b14eef8190314864` passed `spotlessApply :common-platform-core:check -PfullCheck linkCheck lintMarkdown --continue` locally in 1m 38s (213 tasks). Common-platform-core executed 370 tests with zero failures, errors, or skips, including branding DELETE identity, strict command schema integers, exact policy/template revision provenance, and both owner-inventory mutation round trips and rejection cases. This focused run qualifies these passive corrections only; exact published-head CI remains separate and no producer, owner protection, terminal composition, or activation proof is claimed. - Passive `CHARACTER_CREATE/1` local reconstruction on develop `ec16942d236053494b4a8d94d94ef8a5a8be0d08`, retained in candidate `4c3318d07de70e74a60eaaf0a4754d4ac2a28f2d`: the locked `spotlessApply check -PfullCheck linkCheck lintMarkdown --continue` run passed in 3m27s (559 tasks: 324 executed, 195 cached, 40 up-to-date). Common-platform-core reports contain 360 tests with zero failures, errors, or skips; the allocation validator passed for 359 sources (356 allocated, three explicit exemptions). The final workflow/proof-status documentation checks passed in 8s. This proves local passive receiving support only; skipped Docker-backed suites receive no physical credit, and producer authentication, owner protections, Entity terminal composition, route activation, and current published-head CI remain separate obligations. 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 1973b6f4de..b8263e91e4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,12 @@ Game Session now carries a default-off source path for current route and publish 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. +### Original StartSession source-protection storage + +The bounded V1003 receiving cut adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. + +Fresh qualification on the receiving cut based on published Entity parent `6d93e3466b51079cb132d103b80b07dc1d3d0794` passes all 13 focused PostgreSQL cases with zero failures, errors or skips. The canonical gate also passes actual jOOQ generation, integration-source compilation, formatting, Checkstyle, SpotBugs, link checking and Markdown lint (2m47s; 86 tasks, 77 executed and 9 from cache). Only the two selected storage suites executed; this is not a full Account integration run or rebuilt packaged-runtime proof. The focused [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) defines eleven PostgreSQL cases, including unchanged retained rows/OIDs/checksums, complete original tuple and nested issuance binding, exact current replay, precision-sensitive expiry, source-writer exclusion, immutable rows and failed terminal release. The [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) defines two cases covering identity, pending exclusion, currentness and exact terminal integrity. These fixtures explicitly stipulate upstream Account/World/Game Session data with upstream producer triggers disabled; the protection and writer guards under test stay enabled. The fresh execution qualifies these storage fixtures only; historic whole-carrier results do not qualify additional cut behavior. Genuine source currentness, authenticated owner production and terminal settlement, continuous admission protection, activation, actor placement and region delivery remain unproved. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local storage consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). + ### Entity character-creation denial The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 4cc2303bb6..a464eaa827 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -3,26 +3,34 @@ import argparse import dataclasses +import json import os import re +import subprocess import sys import tempfile from pathlib import Path -VERSION_RE = re.compile(r"^V(?P[0-9]+(?:\.[0-9]+)*)__.+\.(?:java|sql)$") +VERSION_RE = re.compile(r"^V(?P[0-9]+(?:[._][0-9]+)*)__.+\.(?:java|sql)$") +MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/migration/") +RUNTIME_DEPENDENCY_RE = re.compile( + r'(?:implementation|api|runtimeOnly)\s*\(\s*project\(\s*":([^\"]+)"' + r'|dependencies\.add\(\s*"(?:implementation|api|runtimeOnly)"\s*,\s*project\.project\(\s*":([^\"]+)"' +) +PLUGIN_RE = re.compile(r'(?:\bid|pluginManager\.apply)\(\s*"([^\"]+)"\s*\)') +Snapshot = dict[str, bytes] @dataclasses.dataclass(frozen=True) class MigrationFile: - path: Path - root: Path - project: Path + path: str + project: str version_text: str version_key: tuple[int, ...] def normalize_version(version_text: str) -> tuple[int, ...]: - parts = [int(part) for part in version_text.split(".")] + parts = [int(part) for part in re.split(r"[._]", version_text)] while len(parts) > 1 and parts[-1] == 0: parts.pop() return tuple(parts) @@ -32,93 +40,137 @@ def version_label(version_key: tuple[int, ...]) -> str: return ".".join(str(part) for part in version_key) -def project_label(project_root: Path, repo_root: Path) -> str: - return project_root.relative_to(repo_root).as_posix() - - -def discover_migration_files(repo_root: Path) -> list[MigrationFile]: - services_dir = repo_root / "services" - if not services_dir.is_dir(): - return [] - - discovered: list[MigrationFile] = [] - sql_paths = services_dir.glob("*/src/main/resources/db/migration/**/V*__*.sql") - java_paths = services_dir.glob("*/src/main/java/db/migration/**/V*__*.java") - for path in [*sql_paths, *java_paths]: - if not path.is_file(): - continue - rel_path = path.relative_to(repo_root).as_posix() - is_sql = "src/main/resources/db/migration" in rel_path - is_java = "src/main/java/db/migration" in rel_path - if not is_sql and not is_java: - continue - - match = VERSION_RE.match(path.name) - if match is None: - continue - - service_name = path.relative_to(repo_root).parts[1] - project_root = repo_root / "services" / service_name - if is_java: - java_root = project_root / "src/main/java/db/migration" - relative_parent = path.parent.relative_to(java_root) - logical_root = project_root / "src/main/resources/db/migration" / relative_parent - else: - logical_root = path.parent - version_text = match.group("version") - discovered.append( - MigrationFile( - path=path, - root=logical_root, - project=project_root, - version_text=version_text, - version_key=normalize_version(version_text), - ) - ) - +def relevant_path(path: str) -> bool: + return bool(MIGRATION_PATH_RE.match(path)) or ( + path.startswith("services/") + and (path.endswith("/build.gradle.kts") or re.search(r"/src/main/resources/application[^/]*\.ya?ml$", path)) + ) or (path.startswith("buildSrc/") and path.endswith((".kt", ".kts"))) + + +def current_snapshot(repo_root: Path) -> Snapshot: + paths = [*repo_root.glob("services/*/build.gradle.kts"), + *repo_root.glob("services/*/src/main/resources/application*.y*ml"), + *repo_root.glob("services/*/src/main/resources/db/migration/**/*"), + *repo_root.glob("services/*/src/main/java/db/migration/**/*"), + *repo_root.glob("buildSrc/**/*.kt"), *repo_root.glob("buildSrc/**/*.kts")] + return {path.relative_to(repo_root).as_posix(): path.read_bytes() for path in paths if path.is_file()} + + +def git(repo_root: Path, *args: str) -> bytes: + result = subprocess.run(["git", "-C", str(repo_root), *args], capture_output=True, check=False) + if result.returncode: + raise ValueError(result.stderr.decode().strip() or f"git {' '.join(args)} failed") + return result.stdout + + +def parent_snapshot(repo_root: Path, base_ref: str) -> Snapshot: + # A branch name can move while validation runs. Require the caller's pinned commit. + if not re.fullmatch(r"[0-9a-fA-F]{40}", base_ref): + raise ValueError("--base-ref must be a full immutable 40-character commit SHA") + commit = git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}").decode().strip() + if commit.lower() != base_ref.lower(): + raise ValueError("--base-ref must identify a commit directly") + paths = git(repo_root, "ls-tree", "-r", "--name-only", commit, "services", "buildSrc").decode().splitlines() + return {path: git(repo_root, "show", f"{commit}:{path}") for path in paths if relevant_path(path)} + + +def discover_migration_files(snapshot: Snapshot) -> list[MigrationFile]: + discovered = [] + for path in sorted(snapshot): + project_match = MIGRATION_PATH_RE.match(path) + version_match = VERSION_RE.match(Path(path).name) + if project_match and version_match: + text = version_match.group("version") + discovered.append(MigrationFile(path, project_match.group(1), text, normalize_version(text))) return discovered -def collect_issues(repo_root: Path) -> tuple[list[str], int, int]: - discovered = discover_migration_files(repo_root) - grouped: dict[Path, dict[Path, list[MigrationFile]]] = {} - for item in discovered: - grouped.setdefault(item.project, {}).setdefault(item.root, []).append(item) - - issues: list[str] = [] - for project_root in sorted(grouped, key=lambda path: path.relative_to(repo_root).as_posix()): - roots = grouped[project_root] - service_label = project_label(project_root, repo_root) - seen_versions: dict[tuple[int, ...], MigrationFile] = {} - highest_seen: tuple[int, ...] | None = None - for root in sorted( - roots, - key=lambda path: (len(path.relative_to(project_root).parts), path.relative_to(project_root).as_posix()), - ): - for item in sorted(roots[root], key=lambda migration: (migration.version_key, migration.path.name)): - existing = seen_versions.get(item.version_key) - if existing is not None: - issues.append( - f"{service_label} ({root.relative_to(project_root).as_posix()}): " - f"duplicate version V{item.version_text} in {item.path.relative_to(repo_root).as_posix()} " - f"also appears in {existing.path.relative_to(repo_root).as_posix()}" - ) - continue - - seen_versions[item.version_key] = item - - if highest_seen is not None and item.version_key <= highest_seen: - issues.append( - f"{service_label} ({root.relative_to(project_root).as_posix()}): " - f"version V{item.version_text} in {item.path.relative_to(repo_root).as_posix()} " - f"is out of order after V{version_label(highest_seen)}" - ) - continue - - if highest_seen is None or item.version_key > highest_seen: - highest_seen = item.version_key - - return issues, len(grouped), len(discovered) +def saga_adopters(snapshot: Snapshot) -> set[str]: + """Read existing runtime dependencies and composed convention plugins, not classifications. + + This follows the repository's literal Kotlin DSL wiring. Test dependencies are + deliberately excluded: they do not put Saga resources on startup classpaths. + """ + registration = snapshot.get("buildSrc/build.gradle.kts", b"").decode() + plugin_sources: dict[str, str] = {} + for plugin_id, class_name in re.findall( + r'id\s*=\s*"([^\"]+)"\s+implementationClass\s*=\s*"([^\"]+)"', registration + ): + path = "buildSrc/src/main/kotlin/" + class_name.replace(".", "/") + ".kt" + if path not in snapshot: + raise ValueError(f"missing convention source for {plugin_id}: {path}") + plugin_sources[plugin_id] = snapshot[path].decode() + + module_sources = {path.split("/")[1]: data.decode() for path, data in snapshot.items() + if re.fullmatch(r"services/[^/]+/build.gradle.kts", path)} + + def reaches_saga(source: str, visited: set[str]) -> bool: + for dependency in RUNTIME_DEPENDENCY_RE.findall(source): + module = next(part for part in dependency if part) + if module == "common-saga": + return True + key = "module:" + module + if (key not in visited and module in module_sources + and reaches_saga(module_sources[module], visited | {key})): + return True + for plugin in PLUGIN_RE.findall(source): + key = "plugin:" + plugin + if (key not in visited and plugin in plugin_sources + and reaches_saga(plugin_sources[plugin], visited | {key})): + return True + return False + + adopters = set() + for project, source in module_sources.items(): + # Flyway scans nested packages below db/migration, so the parent location + # exposes Saga resources too, even without a redundant explicit saga location. + locations = [data.decode() for path, data in snapshot.items() + if re.fullmatch(rf"services/{re.escape(project)}/src/main/resources/application[^/]*\.ya?ml", path)] + if (any(re.search(r"classpath:db/migration(?:/saga)?(?:[\s,\"']|$)", text) for text in locations) + and reaches_saga(source, {"module:" + project})): + adopters.add(project) + return adopters + + +def effective_sets(snapshot: Snapshot) -> tuple[dict[str, list[MigrationFile]], list[MigrationFile]]: + migrations = discover_migration_files(snapshot) + grouped: dict[str, list[MigrationFile]] = {} + for item in migrations: + grouped.setdefault(item.project, []).append(item) + shared = grouped.get("common-saga", []) + for adopter in saga_adopters(snapshot): + grouped.setdefault(adopter, []).extend(shared) + return grouped, migrations + + +def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str], int, int]: + grouped, migrations = effective_sets(current) + parent_grouped, parent_migrations = effective_sets(parent) if parent is not None else ({}, []) + issues = [] + for project, items in sorted(grouped.items()): + seen: dict[tuple[int, ...], MigrationFile] = {} + for item in items: + existing = seen.get(item.version_key) + if existing: + issues.append(f"services/{project}: duplicate version V{item.version_text} in {item.path} " + f"also appears in {existing.path}") + else: + seen[item.version_key] = item + + previous = parent_grouped.get(project, []) + frontier = max((item.version_key for item in previous), default=None) + for item in items: + if parent is not None and item.path not in parent and frontier is not None and item.version_key <= frontier: + issues.append(f"services/{project}: new migration {item.path} (V{item.version_text}) " + f"must exceed effective parent frontier V{version_label(frontier)}") + + # Treat parent histories conservatively as applied; never rewrite their names/checksums. + for item in parent_migrations: + if item.path not in current: + issues.append(f"historical migration removed or renamed: {item.path}") + elif parent is not None and current[item.path] != parent[item.path]: + issues.append(f"historical migration content changed: {item.path}") + return issues, len(grouped), len(migrations) def make_fixture(root: Path, relative_paths: list[str]) -> None: @@ -129,62 +181,100 @@ def make_fixture(root: Path, relative_paths: list[str]) -> None: def run_self_test() -> None: - with tempfile.TemporaryDirectory() as tmp: - repo_root = Path(tmp) - make_fixture( - repo_root, - [ - "services/clean-service/src/main/resources/db/migration/V1__init.sql", - "services/clean-service/src/main/java/db/migration/V2__next.java", - ], - ) - issues, _, _ = collect_issues(repo_root) - if issues: - raise AssertionError(f"clean fixture unexpectedly failed: {issues}") + local = "services/example-service/src/main/resources/db/migration/" + shared = "services/common-saga/src/main/resources/db/migration/saga/" + wiring = { + "services/example-service/build.gradle.kts": b'dependencies { implementation(project(":common-saga")) }', + "services/example-service/src/main/resources/application.yml": b'spring:\n flyway:\n locations: classpath:db/migration,classpath:db/migration/saga\n', + } + history = {**wiring, local + "V1__init.sql": b"-- local\n", shared + "V1002__saga.sql": b"-- shared\n"} + + def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str | None) -> None: + issues, _, _ = collect_issues(current, parent) + if (expected is None and issues) or (expected is not None and not any(expected in issue for issue in issues)): + raise AssertionError(f"{label}: expected {expected!r}, got {issues}") + + check("unchanged legacy history", history, history, None) + check("duplicate-only without a base", history, None, None) + check("new low local", {**history, local + "V2__new.sql": b"-- new"}, history, "frontier V1002") + check("forward local", {**history, local + "V1003__new.sql": b"-- new"}, history, None) + advanced = {**history, local + "V1005__later.sql": b"-- later"} + check("shared below adopter frontier", {**advanced, shared + "V1004__new.sql": b"-- new"}, advanced, "frontier V1005") + check("forward shared", {**advanced, shared + "V1006__new.sql": b"-- new"}, advanced, None) + check("combined duplicate", {**history, local + "V1002__duplicate.sql": b"-- dup"}, history, "duplicate version V1002") + check("normalized duplicate", {**history, local + "V1002_0__duplicate.sql": b"-- dup"}, history, "duplicate version V1002") + check("changed history", {**history, local + "V1__init.sql": b"-- rewritten"}, history, "content changed") + check("removed history", {path: data for path, data in history.items() if path != local + "V1__init.sql"}, history, "removed or renamed") + check("java/sql duplicate", {**history, "services/example-service/src/main/java/db/migration/V1__dup.java": b"// dup"}, history, "duplicate version V1") + + # Exercise the actual composed convention wiring and exclude test-only dependencies. + conventions = { + "buildSrc/build.gradle.kts": b'id = "base"\nimplementationClass = "example.Base"\nid = "composed"\nimplementationClass = "example.Composed"', + "buildSrc/src/main/kotlin/example/Base.kt": b'dependencies.add("implementation", project.project(":common-saga"))', + "buildSrc/src/main/kotlin/example/Composed.kt": b'pluginManager.apply("base")', + } + composed = {**history, **conventions, "services/example-service/build.gradle.kts": b'plugins { id("composed") }'} + check("composed runtime convention", {**composed, local + "V2__new.sql": b"-- new"}, composed, "frontier V1002") + test_only = {**history, "services/example-service/build.gradle.kts": b'testImplementation(project(":common-saga"))'} + check("test-only dependency", {**test_only, local + "V2__new.sql": b"-- new"}, test_only, None) + second_local = "services/second-service/src/main/resources/db/migration/" + multiple = {**history, "services/second-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], + "services/second-service/src/main/resources/application.yml": wiring["services/example-service/src/main/resources/application.yml"], + second_local + "V2000__later.sql": b"-- later"} + check("every adopter frontier", {**multiple, shared + "V1003__new.sql": b"-- new"}, multiple, "frontier V2000") with tempfile.TemporaryDirectory() as tmp: - repo_root = Path(tmp) - make_fixture( - repo_root, - [ - "services/duplicate-service/src/main/resources/db/migration/V1__init.sql", - "services/duplicate-service/src/main/java/db/migration/V1__dup.java", - ], - ) - issues, _, _ = collect_issues(repo_root) - if not any("duplicate version V1" in issue for issue in issues): - raise AssertionError(f"duplicate fixture did not fail as expected: {issues}") + root = Path(tmp) + for path, data in history.items(): + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + git(root, "init", "-q") + git(root, "add", ".") + git(root, "-c", "user.name=Flyway fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "history") + base = git(root, "rev-parse", "HEAD").decode().strip() + make_fixture(root, [local + "V2__new.sql"]) + check("immutable git parent and worktree addition", current_snapshot(root), parent_snapshot(root, base), "frontier V1002") + try: + parent_snapshot(root, "HEAD") + except ValueError: + pass + else: + raise AssertionError("mutable base ref was accepted") with tempfile.TemporaryDirectory() as tmp: - repo_root = Path(tmp) - make_fixture( - repo_root, - [ - "services/order-service/src/main/resources/db/migration/V2__init.sql", - "services/order-service/src/main/resources/db/migration/saga/V1__saga.sql", - ], - ) - issues, _, _ = collect_issues(repo_root) - if not any("out of order" in issue for issue in issues): - raise AssertionError(f"out-of-order fixture did not fail as expected: {issues}") + event_path = Path(tmp) / "event.json" + sha = "1" * 40 + for event, expected in [({"pull_request": {"base": {"sha": sha}}}, sha), + ({"before": sha}, sha), ({"before": "0" * 40}, None), ({}, None)]: + event_path.write_text(json.dumps(event), encoding="utf-8") + if event_base_ref(str(event_path)) != expected: + raise AssertionError(f"unexpected event base for {event}") print("Flyway migration sanity checker self-test passed.") +def event_base_ref(event_path: str | None) -> str | None: + if not event_path: + return None + event = json.loads(Path(event_path).read_text(encoding="utf-8")) + pull_request = event.get("pull_request") + if isinstance(pull_request, dict): + return pull_request.get("base", {}).get("sha") + before = event.get("before") + # A newly created branch has no parent history in the push event. + return before if before and before != "0" * 40 else None + + def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Check Flyway migration versions across FireMUD services.") - parser.add_argument( - "--root", - default=Path(os.environ.get("FIREMUD_REPO_ROOT", Path(__file__).resolve().parents[2])), - type=Path, - help="Repository root to scan. Defaults to the FireMUD checkout root.", - ) - parser.add_argument( - "--self-test", - action="store_true", - help="Run a small built-in validation suite against temporary fixtures.", - ) - return parser.parse_args() + parser = argparse.ArgumentParser(description="Check combined Flyway histories and forward-only additions against a pinned parent.") + parser.add_argument("--root", default=Path(os.environ.get("FIREMUD_REPO_ROOT", Path(__file__).resolve().parents[2])), type=Path, + help="Repository root to scan. Defaults to the FireMUD checkout root.") + parser.add_argument("--base-ref", default=os.environ.get("FIREMUD_FLYWAY_BASE_REF"), + help="Full immutable parent commit SHA; defaults to FIREMUD_FLYWAY_BASE_REF or GitHub event base metadata.") + parser.add_argument("--self-test", action="store_true", help="Run focused validation against temporary fixtures.") + args = parser.parse_args() + return args def main() -> int: @@ -192,18 +282,25 @@ def main() -> int: if args.self_test: run_self_test() return 0 - - repo_root = args.root.resolve() - issues, project_count, file_count = collect_issues(repo_root) + root = args.root.resolve() + try: + base_ref = args.base_ref or event_base_ref(os.environ.get("GITHUB_EVENT_PATH")) + parent = parent_snapshot(root, base_ref) if base_ref else None + issues, project_count, file_count = collect_issues(current_snapshot(root), parent) + except (ValueError, OSError, TypeError) as error: + print(f"Flyway migration sanity check failed: {error}", file=sys.stderr) + return 1 if issues: print("Flyway migration sanity check failed:", file=sys.stderr) for issue in issues: print(f"- {issue}", file=sys.stderr) return 1 - - print( - f"Flyway migration sanity check passed: {project_count} migration sets, {file_count} versioned files." - ) + if base_ref: + print(f"Flyway migration sanity check passed: {project_count} migration sets, {file_count} versioned files; parent {base_ref}.") + else: + print(f"Flyway duplicate-version check passed: {project_count} migration sets, {file_count} versioned files. " + "Parent frontier comparison and history preservation checks unavailable without --base-ref " + "or FIREMUD_FLYWAY_BASE_REF (or GitHub event base metadata).") return 0 diff --git a/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql new file mode 100644 index 0000000000..1529026b92 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql @@ -0,0 +1,1460 @@ +-- Additive receiving Account admission and activation source protections after the canonical +-- capture (V158), World participation (V159), original attempt (V160), and independent source +-- fence (V160.1) owners. No predecessor, retained row, checksum, or owner identity is rewritten. +-- Complete original tuple projection and the independent nested issuance-operation identity +-- are installed directly; this migration never installs the superseded scalar projection guard. +-- These storage/integrity boundaries do not register runtime authority or authenticate producers. + +-- Distinct Account source protection through original Game Session admission. World +-- settlement and original-attempt observation expiry never settle this participation. +-- These integrity guards do not authenticate a producer or Game Session terminal RPC. +CREATE TABLE account_start_session_admission_protections ( + protection_id UUID PRIMARY KEY CHECK (protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE CHECK (protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + original_post_authorization_tuple BYTEA NOT NULL CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 262144), + game_session_owner_mutation_id UUID NOT NULL UNIQUE CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + world_admission_hold_identity_bytes BYTEA NOT NULL CHECK (octet_length(world_admission_hold_identity_bytes) BETWEEN 1 AND 262144), + request_binding_bytes BYTEA NOT NULL CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 1048576), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE account_start_session_admission_protection_sources ( + protection_id UUID NOT NULL REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (protection_id, source_key) +); +CREATE INDEX account_ss_admission_sources_by_key + ON account_start_session_admission_protection_sources(source_key, protection_id); + +CREATE TABLE account_start_session_admission_protection_settlements ( + protection_id UUID PRIMARY KEY REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 25165824), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_is_settled(protection_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS (SELECT 1 FROM account_start_session_admission_protection_settlements + WHERE protection_id = protection_value) +$$; + +-- Called only after the owning writer has locked its canonical source-key set. This +-- shared addition preserves the independently assembled World and other owner guards. +CREATE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; + +-- Account currentness must independently reconstruct the exact live original actor, +-- registry, signer and source capture before invoking this integrity boundary. SQL +-- validates retained bindings; neither a capture nor a historical observation grants +-- admission, and a gap requires the producer's fresh unchanged-source validation. +CREATE FUNCTION account_ss_admission_assert_current( + original account_start_session_admission_protections, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + snapshot_value JSONB; + tuple_value JSONB; + request_value JSONB; + hold_value JSONB; + hold_request JSONB; + projection_value JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + keys TEXT[]; +BEGIN + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id THEN + RAISE EXCEPTION 'Admission protection requires the exact original source snapshot' USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + PERFORM protection_id FROM account_start_session_admission_protections + WHERE protection_id = original.protection_id FOR UPDATE NOWAIT; + -- Always check actual database time after every lock, including exact recovery. + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() + OR account_ss_admission_is_settled(original.protection_id) THEN + RAISE EXCEPTION 'Original StartSession admission protection is not current' + USING ERRCODE = '23514'; + END IF; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR world_parent.participation_fence IS DISTINCT FROM original.account_world_participation_fence + OR world_parent.control_plane_request_id IS DISTINCT FROM original.control_plane_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM original.original_post_authorization_tuple + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR world_parent.target_namespace IS DISTINCT FROM original.target_namespace + OR world_parent.canonical_tenant_id IS DISTINCT FROM original.canonical_tenant_id + OR world_parent.canonical_game_instance_id IS DISTINCT FROM original.canonical_game_instance_id + OR observation.target_namespace IS DISTINCT FROM original.target_namespace + OR observation.game_session_owner_mutation_id IS DISTINCT FROM original.game_session_owner_mutation_id + OR observation.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR observation.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR observation.original_lease_expires_at IS DISTINCT FROM original.original_lease_expires_at + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence THEN + RAISE EXCEPTION 'Original StartSession admission protection differs from its retained owner bindings' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(original.original_post_authorization_tuple, 'UTF8')::JSONB; + IF tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB THEN + RAISE EXCEPTION 'Admission tuple differs from original Account issuance' USING ERRCODE = '23514'; + END IF; + projection_value := convert_from(original.account_redemption_projection, 'UTF8')::JSONB; + IF original.account_redemption_projection IS DISTINCT FROM original.original_post_authorization_tuple + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT THEN + RAISE EXCEPTION 'Admission projection differs from complete original Account redemption' USING ERRCODE = '23514'; + END IF; + request_value := convert_from(original.request_binding_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Admission request binding is not an object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 10 + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-admission-protection-request/v1' + OR request_value->>'originalPostAuthorizationTupleBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'accountRedemptionProjectionBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM original.account_world_participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR request_value->>'worldAdmissionHoldIdentityBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') THEN + RAISE EXCEPTION 'Admission request binding differs from exact immutable selectors' USING ERRCODE = '23514'; + END IF; + hold_value := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + hold_request := convert_from(decode(hold_value->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF hold_value->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' + OR (SELECT count(*) FROM jsonb_object_keys(hold_value)) <> 5 + OR NOT (hold_value ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR (hold_value->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_value->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_value->>'holdBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') + OR hold_request->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR hold_request->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Admission hold identity differs from original instance and request' USING ERRCODE = '23514'; + END IF; + -- Original World source children remain immutable even when World has settled. + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id) <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Admission protection has incomplete or extra source children' USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Admission source child differs from complete original capture' USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession admission expiry elapsed during integrity validation' USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_admission_read_current_exact(protection_value UUID, fence_value BIGINT, request_value BYTEA) +RETURNS SETOF account_start_session_admission_protections LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = protection_value AND protection_fence = fence_value; + IF original.request_binding_bytes IS DISTINCT FROM request_value THEN + RAISE EXCEPTION 'Original admission recovery binding differs' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NEXT original; +END; +$$; + +CREATE FUNCTION account_ss_admission_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'Admission protection must be created by its producer transaction' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(NEW::account_start_session_admission_protections, FALSE); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + IF producer IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'Admission sources must be exact same-producer children' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_admission_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession admission evidence is append-only' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_admission_validate BEFORE INSERT ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_insert_guard(); +CREATE TRIGGER account_ss_admission_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_validate BEFORE INSERT ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_source_insert_guard(); +CREATE TRIGGER account_ss_admission_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_admission_complete AFTER INSERT ON account_start_session_admission_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_admission_complete_guard(); +CREATE TRIGGER account_ss_admission_settlements_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +-- The authenticated exact Game Session terminal API is not yet composed. Reject every +-- settlement insertion until its sealed complete terminal binding guard replaces this +-- unpublished gate. An outcome assertion alone can never release source protection. +CREATE TRIGGER account_ss_admission_settlements_disabled BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_settlements_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, + E' PERFORM account_ss_admission_assert_no_pending(source_keys);\n' || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission source-change anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ PERFORM account_ss_admission_assert_no_pending( + ARRAY(SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id)); +$guard$ || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission disclosure anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key FROM account_draft_authorization_source_locks source_lock + JOIN (SELECT OLD.source_key AS source_key UNION + SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + PERFORM account_ss_admission_assert_no_pending(ARRAY( + SELECT OLD.source_key UNION SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id)); + END IF; +$guard$ || anchor); +END; +$migration$; +-- [jooq ignore end] + + +-- Immutable Account settlement for the exact original Game Session admission proof. +-- This guard validates retained structure and integrity only. It does not authenticate +-- the remote producer; the internal Game Session client owns that provenance boundary. +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_admission_protections%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + existing account_start_session_admission_protection_settlements%ROWTYPE; + terminal_json JSONB; + evidence_json JSONB; + hold_json JSONB; + hold_request_json JSONB; + snapshot_json JSONB; + evidence_bytes BYTEA; + owner_proof_bytes BYTEA; + canonical_outer TEXT; + canonical_evidence TEXT; + canonical_request TEXT; + canonical_hold TEXT; + canonical_hold_request TEXT; + source_vector TEXT; + source_count BIGINT; + source_bytes_total BIGINT; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + position_value INTEGER := 1; + frame_next_position INTEGER; + parsed BYTEA; + marker TEXT; + proof_schema TEXT; + proof_hold_bytes BYTEA; + proof_outcome TEXT; + pointer_marker TEXT; + pointer_text TEXT; + audit_marker TEXT; + audit_text TEXT; + digest_marker TEXT; + proof_digest TEXT; + abort_value TEXT; + terminal_marker TEXT; + terminal_at_text TEXT; + terminal_stem TEXT; + expected_pointer NUMERIC; + prior_pointer NUMERIC; + original_request JSONB; +BEGIN + SELECT * INTO STRICT original + FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + + IF NEW.outcome NOT IN ('COMMITTED', 'ABORTED') + OR NEW.terminal_bytes IS NULL + OR octet_length(NEW.terminal_bytes) NOT BETWEEN 1 AND 25165824 + OR NEW.terminal_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') THEN + RAISE EXCEPTION 'Malformed original StartSession admission settlement' + USING ERRCODE = '23514'; + END IF; + + -- Reconstructing the complete outer object makes duplicate keys, alternate escaping, + -- trailing input, and non-RFC8785 ordering fail byte-for-byte. + terminal_json := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(terminal_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal_json)) <> 3 + OR NOT (terminal_json ?& ARRAY[ + 'schema', 'canonicalAccountProtectionEvidenceBytesBase64', + 'canonicalGameSessionOwnerProofBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(terminal_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR terminal_json->>'schema' IS DISTINCT FROM + 'account-start-session-admission-protection-settlement/v1' THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not the closed envelope' + USING ERRCODE = '23514'; + END IF; + evidence_bytes := decode(terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64', 'base64'); + owner_proof_bytes := decode(terminal_json->>'canonicalGameSessionOwnerProofBytesBase64', 'base64'); + IF octet_length(evidence_bytes) NOT BETWEEN 1 AND 8388608 + OR octet_length(owner_proof_bytes) NOT BETWEEN 1 AND 66048 + OR regexp_replace(encode(evidence_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64' + OR regexp_replace(encode(owner_proof_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalGameSessionOwnerProofBytesBase64' THEN + RAISE EXCEPTION 'Original StartSession admission settlement has invalid canonical Base64' + USING ERRCODE = '23514'; + END IF; + canonical_outer := '{"canonicalAccountProtectionEvidenceBytesBase64":"' + || (terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64') + || '","canonicalGameSessionOwnerProofBytesBase64":"' + || (terminal_json->>'canonicalGameSessionOwnerProofBytesBase64') + || '","schema":"account-start-session-admission-protection-settlement/v1"}'; + IF convert_to(canonical_outer, 'UTF8') IS DISTINCT FROM NEW.terminal_bytes THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT capture + FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR octet_length(capture.canonical_capture_bytes) NOT BETWEEN 1 AND 262144 + OR octet_length(capture.canonical_snapshot_bytes) NOT BETWEEN 1 AND 245760 + OR capture.canonical_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_snapshot_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission capture differs from retained protection' + USING ERRCODE = '23514'; + END IF; + + -- The immutable Account request is a closed ten-string object. Rebuild its canonical + -- representation from the retained parent so the settlement cannot bind a projection. + canonical_request := '{"accountRedemptionProjectionBytesBase64":"' + || regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + || '","accountWorldParticipationFence":"' + || original.account_world_participation_fence::TEXT + || '","accountWorldParticipationId":"' + || original.account_world_participation_id::TEXT + || '","gameSessionOwnerAttemptId":"' + || original.game_session_owner_attempt_id::TEXT + || '","gameSessionOwnerFence":"' + || original.game_session_owner_fence::TEXT + || '","gameSessionOwnerMutationId":"' + || original.game_session_owner_mutation_id::TEXT + || '","originalLeaseExpiresAt":"' + || to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + || '","originalPostAuthorizationTupleBytesBase64":"' + || regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-request/v1"' + || ',"worldAdmissionHoldIdentityBytesBase64":"' + || regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') + || '"}'; + IF octet_length(original.request_binding_bytes) NOT BETWEEN 1 AND 786432 + OR octet_length(original.world_admission_hold_identity_bytes) NOT BETWEEN 1 AND 65536 + OR convert_to(canonical_request, 'UTF8') IS DISTINCT FROM original.request_binding_bytes + OR original.request_binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.request_binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission request is not its exact canonical binding' + USING ERRCODE = '23514'; + END IF; + + snapshot_json := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_json->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_json->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id + OR jsonb_typeof(snapshot_json->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_json->'sourceVector') NOT BETWEEN 1 AND 256 THEN + RAISE EXCEPTION 'Original StartSession admission source capture is incomplete' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO source_count + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + SELECT COALESCE(sum(octet_length(source_evidence)), 0) INTO source_bytes_total + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + IF source_count IS DISTINCT FROM jsonb_array_length(snapshot_json->'sourceVector')::BIGINT + OR source_bytes_total > 4194304 THEN + RAISE EXCEPTION 'Original StartSession admission source children are incomplete' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_json->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Original StartSession source vector has a non-string member' + USING ERRCODE = '23514'; + END IF; + source_bytes := decode(source_value #>> '{}', 'base64'); + IF octet_length(source_bytes) NOT BETWEEN 1 AND 131072 + OR regexp_replace(encode(source_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM source_value #>> '{}' THEN + RAISE EXCEPTION 'Original StartSession source vector has noncanonical bytes' + USING ERRCODE = '23514'; + END IF; + source_key_value := account_start_session_world_participation_source_key(source_bytes); + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Original StartSession source vector is duplicated or out of order' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Original StartSession source child differs from its immutable capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + + SELECT string_agg( + '"' || regexp_replace(encode(source.source_evidence, 'base64'), E'[\n\r]', '', 'g') || '"', + ',' ORDER BY account_publication_authorization_source_sort_key(source.source_key)) + INTO source_vector + FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id; + canonical_evidence := '{"accountProtectionFence":"' || original.protection_fence::TEXT + || '","accountProtectionId":"' || original.protection_id::TEXT + || '","originalSourceCaptureReferenceBytesBase64":"' + || regexp_replace(encode(capture.canonical_capture_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","originalSourceCaptureReferenceSha256":"' || capture.canonical_sha256 + || '","requestBytesBase64":"' + || regexp_replace(encode(original.request_binding_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-evidence/v1"' + || ',"sourceEvidenceVector":[' || source_vector || ']}'; + IF convert_to(canonical_evidence, 'UTF8') IS DISTINCT FROM evidence_bytes THEN + RAISE EXCEPTION 'Original StartSession admission evidence differs from its full retained binding' + USING ERRCODE = '23514'; + END IF; + + -- Validate the exact retained World hold identity and request, including the original + -- target and the pointer precondition used to derive a committed next pointer. + hold_json := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(hold_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_json)) <> 5 + OR NOT (hold_json ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR hold_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is malformed' + USING ERRCODE = '23514'; + END IF; + IF (hold_json->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_json->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_json->>'holdId' IS DISTINCT FROM (hold_json->>'holdId')::UUID::TEXT + OR hold_json->>'holdFence' IS DISTINCT FROM (hold_json->>'holdFence')::UUID::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is nil' + USING ERRCODE = '23514'; + END IF; + hold_request_json := convert_from(decode(hold_json->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF regexp_replace(encode(decode(hold_json->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM hold_json->>'requestBytesBase64' + OR hold_json->>'holdBindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(decode(hold_json->>'requestBytesBase64', 'base64')), 'hex') + OR jsonb_typeof(hold_request_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json)) <> 2 + OR NOT (hold_request_json ?& ARRAY['schema', 'request']) + OR hold_request_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json->'request')) <> 14 + OR NOT (hold_request_json->'request' ?& ARRAY[ + 'activeLifecycleEpoch', 'canonicalGameInstanceId', 'canonicalTenantId', + 'canonicalVersionId', 'expectedCatalogRevision', 'expectedPriorPointerVersion', + 'initialAdmissionOrigin', 'initialAdmissionRequestDigest', + 'initialAdmissionRequestId', 'playableStateNamespaceId', 'playableStateScope', + 'realmId', 'targetNamespace', 'worldSlug']) + OR hold_request_json->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request_json->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request_json->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold request differs from retained protection' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM jsonb_each(hold_request_json->'request') field + WHERE field.key <> 'expectedPriorPointerVersion' + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') NOT IN ('string', 'null') THEN + RAISE EXCEPTION 'Original StartSession hold request fields have invalid JSON types' + USING ERRCODE = '23514'; + END IF; + canonical_hold_request := '{"request":{"activeLifecycleEpoch":' + || to_json(hold_request_json->'request'->>'activeLifecycleEpoch')::TEXT + || ',"canonicalGameInstanceId":' + || to_json(hold_request_json->'request'->>'canonicalGameInstanceId')::TEXT + || ',"canonicalTenantId":' + || to_json(hold_request_json->'request'->>'canonicalTenantId')::TEXT + || ',"canonicalVersionId":' + || to_json(hold_request_json->'request'->>'canonicalVersionId')::TEXT + || ',"expectedCatalogRevision":' + || to_json(hold_request_json->'request'->>'expectedCatalogRevision')::TEXT + || ',"expectedPriorPointerVersion":' + || CASE + WHEN jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'null' + THEN 'null' + ELSE to_json(hold_request_json->'request'->>'expectedPriorPointerVersion')::TEXT + END + || ',"initialAdmissionOrigin":' + || to_json(hold_request_json->'request'->>'initialAdmissionOrigin')::TEXT + || ',"initialAdmissionRequestDigest":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestDigest')::TEXT + || ',"initialAdmissionRequestId":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestId')::TEXT + || ',"playableStateNamespaceId":' + || to_json(hold_request_json->'request'->>'playableStateNamespaceId')::TEXT + || ',"playableStateScope":' + || to_json(hold_request_json->'request'->>'playableStateScope')::TEXT + || ',"realmId":' + || to_json(hold_request_json->'request'->>'realmId')::TEXT + || ',"targetNamespace":' + || to_json(hold_request_json->'request'->>'targetNamespace')::TEXT + || ',"worldSlug":' + || to_json(hold_request_json->'request'->>'worldSlug')::TEXT + || '},"schema":"world-canonical-initial-admission-hold-request/v1"}'; + IF convert_to(canonical_hold_request, 'UTF8') IS DISTINCT FROM + decode(hold_json->>'requestBytesBase64', 'base64') THEN + RAISE EXCEPTION 'Original StartSession hold request is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + canonical_hold := '{"holdBindingDigest":"' || (hold_json->>'holdBindingDigest') + || '","holdFence":"' || (hold_json->>'holdFence') + || '","holdId":"' || (hold_json->>'holdId') + || '","requestBytesBase64":"' || (hold_json->>'requestBytesBase64') + || '","schema":"world-canonical-initial-admission-hold-identity/v1"}'; + IF convert_to(canonical_hold, 'UTF8') IS DISTINCT FROM original.world_admission_hold_identity_bytes THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is not canonical' + USING ERRCODE = '23514'; + END IF; + + -- The actual Game Session codec frames the hold and seven terminal fields. Do not treat + -- its opaque terminal proof digest as permission; only the exact COMMITTED/ABORTED shape + -- below may settle this immutable Account binding. + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + proof_schema := convert_from(parsed, 'UTF8'); + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO proof_hold_bytes, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_outcome := convert_from(parsed, 'UTF8'); + + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_marker := convert_from(parsed, 'UTF8'); + IF pointer_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_text := convert_from(parsed, 'UTF8'); + ELSIF pointer_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal pointer frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_marker := convert_from(parsed, 'UTF8'); + IF audit_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_text := convert_from(parsed, 'UTF8'); + ELSIF audit_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal audit frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + digest_marker := convert_from(parsed, 'UTF8'); + IF digest_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_digest := convert_from(parsed, 'UTF8'); + ELSIF digest_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal digest frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + abort_value := convert_from(parsed, 'UTF8'); + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_marker := convert_from(parsed, 'UTF8'); + IF terminal_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_at_text := convert_from(parsed, 'UTF8'); + ELSIF terminal_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal timestamp frame is malformed' USING ERRCODE = '23514'; + END IF; + IF position_value <> octet_length(owner_proof_bytes) + 1 + OR proof_schema IS DISTINCT FROM 'game-session-canonical-initial-admission-owner-proof/v1' + OR proof_hold_bytes IS DISTINCT FROM original.world_admission_hold_identity_bytes + OR proof_digest IS NULL OR proof_digest !~ '^sha256:[0-9a-f]{64}$' + OR terminal_at_text IS NULL + OR terminal_at_text !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3}|\.[0-9]{6}|\.[0-9]{9})?Z$' + OR terminal_at_text ~ '\.000Z$' + OR terminal_at_text ~ '\.[0-9]{3}000Z$' + OR terminal_at_text ~ '\.[0-9]{6}000Z$' + OR abort_value NOT IN ('true', 'false') THEN + RAISE EXCEPTION 'Original StartSession owner proof is malformed or differs from its hold' + USING ERRCODE = '23514'; + END IF; + -- Validate the calendar/time stem separately. Casting the complete fraction to + -- TIMESTAMPTZ would round nanoseconds to PostgreSQL microseconds and could silently + -- accept noncanonical Java Instant text; the exact frame bytes remain authoritative. + terminal_stem := to_char( + substring(terminal_at_text FROM 1 FOR 19)::TIMESTAMP WITHOUT TIME ZONE, + 'YYYY-MM-DD"T"HH24:MI:SS'); + IF terminal_stem IS DISTINCT FROM substring(terminal_at_text FROM 1 FOR 19) THEN + RAISE EXCEPTION 'Original StartSession owner proof timestamp stem is not normalized' + USING ERRCODE = '23514'; + END IF; + original_request := hold_request_json->'request'; + IF proof_outcome = 'COMMITTED' THEN + IF pointer_marker IS DISTINCT FROM 'PRESENT' + OR pointer_text IS NULL OR pointer_text !~ '^[1-9][0-9]{0,18}$' + OR audit_marker IS DISTINCT FROM 'PRESENT' + OR audit_text IS NULL OR audit_text !~ '^[1-9][0-9]{0,18}$' + OR abort_value IS DISTINCT FROM 'false' THEN + RAISE EXCEPTION 'Committed Game Session terminal proof has invalid outcome fields' + USING ERRCODE = '23514'; + END IF; + IF original_request->>'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND original_request->'expectedPriorPointerVersion' = 'null'::JSONB THEN + expected_pointer := 1; + ELSIF original_request->>'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND jsonb_typeof(original_request->'expectedPriorPointerVersion') = 'string' + AND original_request->>'expectedPriorPointerVersion' ~ '^[1-9][0-9]{0,18}$' THEN + prior_pointer := (original_request->>'expectedPriorPointerVersion')::NUMERIC; + IF prior_pointer >= 9223372036854775807 THEN + RAISE EXCEPTION 'Original StartSession pointer version cannot advance without overflow' + USING ERRCODE = '23514'; + END IF; + expected_pointer := prior_pointer + 1; + ELSE + RAISE EXCEPTION 'Original StartSession hold has an invalid pointer precondition' + USING ERRCODE = '23514'; + END IF; + IF pointer_text::NUMERIC IS DISTINCT FROM expected_pointer THEN + RAISE EXCEPTION 'Committed Game Session terminal proof does not name the exact next pointer' + USING ERRCODE = '23514'; + END IF; + PERFORM audit_text::BIGINT; + IF NEW.outcome IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Account settlement outcome differs from Game Session owner proof' + USING ERRCODE = '23514'; + END IF; + ELSIF proof_outcome = 'ABORTED' THEN + IF pointer_marker IS DISTINCT FROM 'ABSENT' + OR audit_marker IS DISTINCT FROM 'ABSENT' + OR abort_value IS DISTINCT FROM 'true' + OR NEW.outcome IS DISTINCT FROM 'ABORTED' THEN + RAISE EXCEPTION 'Aborted Game Session terminal proof lacks positive durable exclusion' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'Pending or unsupported Game Session owner proof cannot settle protection' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO existing + FROM account_start_session_admission_protection_settlements + WHERE protection_id = NEW.protection_id; + IF FOUND AND (existing.outcome IS DISTINCT FROM NEW.outcome + OR existing.terminal_bytes IS DISTINCT FROM NEW.terminal_bytes + OR existing.terminal_digest IS DISTINCT FROM NEW.terminal_digest) THEN + RAISE EXCEPTION 'Original StartSession admission terminal settlement conflicts with its first receipt' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +DROP TRIGGER account_ss_admission_settlements_disabled + ON account_start_session_admission_protection_settlements; +CREATE TRIGGER account_ss_admission_settlements_validate + BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_settlement_insert_guard(); +-- [jooq ignore end] + + +-- Distinct Account-owned source protection through the exact original World activation. +-- This is immutable storage only: it authenticates no owner and has no release or +-- settlement path. A future exact ACTIVE/ABORTED terminal contract must add that separately. +CREATE TABLE account_start_session_activation_protections ( + activation_protection_id UUID PRIMARY KEY DEFAULT gen_random_uuid() + CHECK (activation_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + activation_protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE + CHECK (activation_protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL + CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 135168), + game_session_owner_mutation_id UUID NOT NULL UNIQUE + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_launch_read_evidence BYTEA NOT NULL + CHECK (octet_length(game_session_launch_read_evidence) BETWEEN 1 AND 42991616), + world_preparing_evidence BYTEA NOT NULL + CHECK (octet_length(world_preparing_evidence) BETWEEN 1 AND 67108864), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + capture_reference_bytes BYTEA NOT NULL + CHECK (octet_length(capture_reference_bytes) BETWEEN 1 AND 262144), + capture_reference_sha256 VARCHAR(64) NOT NULL + CHECK (capture_reference_sha256 ~ '^[0-9a-f]{64}$'), + operation_identity_bytes BYTEA NOT NULL + CHECK (octet_length(operation_identity_bytes) BETWEEN 1 AND 150994944), + operation_identity_digest VARCHAR(71) NOT NULL UNIQUE + CHECK (operation_identity_digest = 'sha256:' || encode(sha256(operation_identity_bytes), 'hex')), + request_binding_bytes BYTEA NOT NULL + CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 150994944), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + acquired_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (isfinite(acquired_at) AND acquired_at < original_lease_expires_at), + CHECK (capture_sha256 = capture_reference_sha256) +); + +CREATE TABLE account_start_session_activation_protection_sources ( + activation_protection_id UUID NOT NULL + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (activation_protection_id, source_key) +); +CREATE INDEX account_ss_activation_sources_by_key + ON account_start_session_activation_protection_sources(source_key, activation_protection_id); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_assert_current( + request_bytes BYTEA, + operation_bytes BYTEA, + operation_digest TEXT, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + retained account_start_session_activation_protections%ROWTYPE; + snapshot_value JSONB; + request_value JSONB; + tuple_value JSONB; + projection_value JSONB; + preparing_value JSONB; + preparing_request JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + tuple_bytes BYTEA; + projection_bytes BYTEA; + preparing_bytes BYTEA; + control_request_id TEXT; + requested_participation_id UUID; + keys TEXT[]; + retained_found BOOLEAN := FALSE; +BEGIN + IF octet_length(request_bytes) NOT BETWEEN 1 AND 150994944 + OR octet_length(operation_bytes) NOT BETWEEN 1 AND 150994944 + OR operation_digest IS DISTINCT FROM 'sha256:' || encode(sha256(operation_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession activation request or operation identity is invalid' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(request_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 12 + OR NOT (request_value ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' THEN + RAISE EXCEPTION 'Original StartSession activation request has an unsupported shape' + USING ERRCODE = '23514'; + END IF; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + tuple_value := convert_from(tuple_bytes, 'UTF8')::JSONB; + control_request_id := tuple_value->>'controlPlaneRequestId'; + requested_participation_id := (request_value->>'accountWorldParticipationId')::UUID; + + -- Source-key locks are acquired in the canonical V129 order before any retained owner, + -- World or activation-protection row is locked. + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id THEN + RAISE EXCEPTION 'Activation protection requires the exact original Account source snapshot' + USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE account_start_session_world_participations.participation_id = requested_participation_id + FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = world_parent.participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO retained FROM account_start_session_activation_protections + WHERE account_start_session_activation_protections.control_plane_request_id = control_request_id + FOR UPDATE NOWAIT; + retained_found := FOUND; + + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + projection_value := convert_from(projection_bytes, 'UTF8')::JSONB; + IF request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM observation.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM observation.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM observation.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(observation.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM world_parent.participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM world_parent.participation_fence::TEXT + OR world_parent.control_plane_request_id IS DISTINCT FROM control_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR observation.target_namespace IS DISTINCT FROM world_parent.target_namespace + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = world_parent.participation_id + AND settlement.outcome = 'COMMITTED') + OR preparing_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing_value->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing_request->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id + OR preparing_request->>'targetNamespace' IS DISTINCT FROM world_parent.target_namespace + OR preparing_request->>'canonicalTenantId' IS DISTINCT FROM world_parent.canonical_tenant_id::TEXT + OR preparing_request->>'canonicalGameInstanceId' IS DISTINCT FROM world_parent.canonical_game_instance_id::TEXT + OR capture.source_version <= 0 OR capture.source_fence <= 0 THEN + RAISE EXCEPTION 'Activation protection differs from committed original World preparation or attempt' + USING ERRCODE = '23514'; + END IF; + + -- Retain the original Account issuance/redemption tuple and complete projection exactly. + IF capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_snapshot_bytes), 'hex') + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR projection_bytes IS DISTINCT FROM tuple_bytes + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT + OR capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection differs from original Account redemption or capture' + USING ERRCODE = '23514'; + END IF; + + IF retained_found AND ( + retained.operation_identity_bytes IS DISTINCT FROM operation_bytes + OR retained.operation_identity_digest IS DISTINCT FROM operation_digest + OR retained.account_world_participation_id IS DISTINCT FROM world_parent.participation_id + OR retained.account_world_participation_fence IS DISTINCT FROM world_parent.participation_fence) THEN + RAISE EXCEPTION 'Original StartSession activation protection conflicts with its immutable binding' + USING ERRCODE = '23514'; + END IF; + + -- The typed Common carrier validates the closed Game Session STARTING result and exact + -- World PREPARING evidence. SQL independently checks finite original authority only after + -- all canonical source and owner/protection row locks have completed. + IF observation.original_lease_expires_at IS DISTINCT FROM + (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR observation.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession activation protection lease is stale or expired' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id) + <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Activation protection has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id + AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Activation protection source child differs from original capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR NEW.world_activation_request_id IS DISTINCT FROM (request_value->>'worldActivationRequestId')::UUID + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + IF producer IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'Activation protection sources must be exact same-producer children' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_activation_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + PERFORM account_ss_activation_assert_current( + original.request_binding_bytes, original.operation_identity_bytes, + original.operation_identity_digest, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable and has no settlement path' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_validate BEFORE INSERT ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_insert_guard(); +CREATE TRIGGER account_ss_activation_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_validate BEFORE INSERT ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_source_insert_guard(); +CREATE TRIGGER account_ss_activation_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_activation_complete AFTER INSERT ON account_start_session_activation_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_activation_complete_guard(); + +-- Existing assembled source-writer guards call this helper after locking their canonical +-- source keys. Keep every admission check installed above and add the permanently pending activation rows. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] + + +-- Append-only resolution of the distinct original StartSession activation source protection. +-- Only an exact authenticated World ACTIVE or fenced ABORTED terminal receipt may be recorded; +-- expiry, missing World state, timeout, generic close, and absence are not terminal outcomes. +CREATE TABLE account_start_session_activation_protection_settlements ( + activation_protection_id UUID PRIMARY KEY + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + activation_protection_fence BIGINT NOT NULL CHECK (activation_protection_fence > 0), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_fence BIGINT NOT NULL CHECK (world_activation_fence > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + account_protection_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 209715264), + terminal_bytes BYTEA NOT NULL + CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 805306368), + terminal_digest VARCHAR(71) NOT NULL + CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() + CHECK (isfinite(settled_at)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + terminal JSONB; + protection_evidence JSONB; + protection_request JSONB; + protection_request_bytes BYTEA; + result_value JSONB; + result_bytes BYTEA; + result_request_bytes BYTEA; + preparing_bytes BYTEA; + preparing_value JSONB; + preparing_request JSONB; + expected_preparing JSONB; + expected_activation_request JSONB; + expected_source_vector JSONB; + source_count BIGINT; + evidence_base64 TEXT; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + terminal := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + evidence_base64 := replace(replace(encode(NEW.account_protection_evidence_bytes, 'base64'), E'\n', ''), E'\r', ''); + protection_evidence := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + protection_request_bytes := decode(protection_evidence->>'requestBytesBase64', 'base64'); + protection_request := convert_from(protection_request_bytes, 'UTF8')::JSONB; + preparing_bytes := decode(protection_request->>'preparingEvidenceBytesBase64', 'base64'); + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + expected_preparing := jsonb_set( + preparing_value, '{request}', preparing_request - 'readRequestId', FALSE); + expected_activation_request := jsonb_build_object( + 'schema', 'world-canonical-instance-activation-request/v1', + 'activationRequestId', original.world_activation_request_id::TEXT, + 'preparingEvidence', expected_preparing); + result_bytes := decode(terminal->>'activationResultBytesBase64', 'base64'); + result_value := convert_from(result_bytes, 'UTF8')::JSONB; + result_request_bytes := decode(result_value->>'requestBytesBase64', 'base64'); + SELECT count(*) INTO source_count + FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = original.activation_protection_id; + SELECT COALESCE( + jsonb_agg( + to_jsonb(replace(replace(encode(source.source_evidence, 'base64'), E'\n', ''), E'\r', '')) + ORDER BY source.source_key), + '[]'::JSONB) + INTO expected_source_vector + FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id; + IF NEW.activation_protection_fence IS DISTINCT FROM original.activation_protection_fence + OR NEW.world_activation_request_id IS DISTINCT FROM original.world_activation_request_id + OR NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') + OR jsonb_typeof(protection_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_evidence)) <> 8 + OR NOT (protection_evidence ?& ARRAY[ + 'schema', 'requestBytesBase64', 'accountProtectionId', 'accountProtectionFence', + 'acquiredAt', 'originalSourceCaptureReferenceBytesBase64', + 'originalSourceCaptureReferenceSha256', 'sourceEvidenceVector']) + OR protection_evidence->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-evidence/v1' + OR protection_evidence->>'accountProtectionId' IS DISTINCT FROM original.activation_protection_id::TEXT + OR protection_evidence->>'accountProtectionFence' IS DISTINCT FROM original.activation_protection_fence::TEXT + OR protection_evidence->>'acquiredAt' IS DISTINCT FROM + to_char(original.acquired_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_evidence->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.request_binding_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_request_bytes IS DISTINCT FROM original.request_binding_bytes + OR jsonb_typeof(protection_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_request)) <> 12 + OR NOT (protection_request ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR protection_request->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' + OR decode(protection_request->>'originalPostAuthorizationTupleBytesBase64', 'base64') + IS DISTINCT FROM original.original_post_authorization_tuple + OR decode(protection_request->>'accountRedemptionProjectionBytesBase64', 'base64') + IS DISTINCT FROM original.account_redemption_projection + OR protection_request->>'gameSessionOwnerMutationId' + IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR protection_request->>'gameSessionOwnerAttemptId' + IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR protection_request->>'gameSessionOwnerFence' + IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR protection_request->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_request->>'accountWorldParticipationId' + IS DISTINCT FROM original.account_world_participation_id::TEXT + OR protection_request->>'accountWorldParticipationFence' + IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR decode(protection_request->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64') + IS DISTINCT FROM original.game_session_launch_read_evidence + OR protection_request->>'worldActivationRequestId' IS DISTINCT FROM original.world_activation_request_id::TEXT + OR protection_request->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.capture_reference_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceSha256' IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR original.capture_reference_sha256 IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR jsonb_typeof(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR source_count <= 0 + OR jsonb_array_length(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM source_count + OR protection_evidence->'sourceEvidenceVector' IS DISTINCT FROM expected_source_vector + OR EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id + AND account_start_session_world_participation_source_key(source.source_evidence) + IS DISTINCT FROM source.source_key) + OR jsonb_typeof(terminal) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal)) <> 8 + OR NOT (terminal ?& ARRAY[ + 'schema', 'activationRequestId', 'accountProtectionId', 'accountProtectionFence', + 'worldActivationFence', 'accountProtectionEvidenceBytesBase64', + 'activationResultBytesBase64', 'activationResultSha256']) + OR terminal->>'schema' IS DISTINCT FROM 'world-original-start-session-activation-terminal-evidence/v1' + OR terminal->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR terminal->>'accountProtectionId' IS DISTINCT FROM NEW.activation_protection_id::TEXT + OR terminal->>'accountProtectionFence' IS DISTINCT FROM NEW.activation_protection_fence::TEXT + OR terminal->>'worldActivationFence' IS DISTINCT FROM NEW.world_activation_fence::TEXT + OR terminal->>'accountProtectionEvidenceBytesBase64' IS DISTINCT FROM evidence_base64 + OR terminal->>'activationResultSha256' IS DISTINCT FROM encode(sha256(result_bytes), 'hex') + OR result_value IS NULL + OR jsonb_typeof(result_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result_value)) <> 8 + OR NOT (result_value ?& ARRAY[ + 'schema', 'activationRequestId', 'requestDigest', 'requestBytesBase64', + 'preparingEvidenceBytesBase64', 'outcome', 'terminalCode', + 'lifecycleEvidenceBytesBase64']) + OR result_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result_value->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR result_value->>'requestDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(result_request_bytes), 'hex') + OR convert_from(result_request_bytes, 'UTF8')::JSONB IS DISTINCT FROM expected_activation_request + OR result_value->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(result_request_bytes, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'outcome' IS DISTINCT FROM NEW.outcome + OR (NEW.outcome = 'COMMITTED' AND result_value->'terminalCode' IS DISTINCT FROM 'null'::JSONB) + OR (NEW.outcome = 'ABORTED' + AND (jsonb_typeof(result_value->'terminalCode') IS DISTINCT FROM 'string' + OR length(result_value->>'terminalCode') = 0)) THEN + RAISE EXCEPTION 'Activation settlement must retain the exact terminal receipt for its protection' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_settlement_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation settlement is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_settlement_validate + BEFORE INSERT ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_insert_guard(); +CREATE TRIGGER account_ss_activation_settlement_immutable + BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); +CREATE TRIGGER account_ss_activation_settlement_no_truncate + BEFORE TRUNCATE ON account_start_session_activation_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); + +CREATE OR REPLACE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable; terminal settlement is separate and append-only' + USING ERRCODE = '23514'; +END; +$$; + +-- Preserve the admission-protection branch and settle activation source guards only when an +-- exact terminal receipt exists. Existing V129 source writers already call this shared function. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_settlements settlement + WHERE settlement.activation_protection_id = protection.activation_protection_id) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..89f9c3c574 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -0,0 +1,1041 @@ +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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * Runs V1003 against the actual Account PostgreSQL schema and assembled source-writer guard. The + * integrity and currentness fixtures seed related owner rows with producer triggers disabled; they + * prove SQL currentness/exclusion/immutability only, not authenticated activation-protection + * production. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionActivationProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() throws Exception { + Fixture fixture = fixture(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + byte[] captureReference = bytes("capture-reference"); + byte[] operationIdentity = bytes("{\"schema\":\"activation-operation-test/v1\"}"); + String captureDigest = hash(captureReference); + String operationDigest = "sha256:" + hash(operationIdentity); + OffsetDateTime expiry = + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() - INTERVAL '1 minute'") + .get(0, OffsetDateTime.class); + OffsetDateTime acquiredAt = expiry.minusMinutes(1); + String expiryText = timestamp(expiry); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + tenantId.toString(), + "2", + "17", + null, + null, + bytes("captured activation source")); + String sourceKey = sourceEvidence.key(); + byte[] sourceEvidenceBytes = sourceEvidence.canonicalBytes(); + byte[] tuple = bytes("synthetic original tuple"); + byte[] projection = bytes("synthetic Account redemption projection"); + byte[] launchRead = bytes("synthetic authenticated STARTING launch read"); + byte[] preparingEvidence = + jsonBytes( + Map.of( + "schema", + "world-canonical-instance-lifecycle-evidence/v1", + "request", + Map.of( + "readRequestId", + UUID.randomUUID().toString(), + "controlPlaneRequestId", + fixture.requestId(), + "targetNamespace", + "test", + "canonicalTenantId", + tenantId.toString(), + "canonicalGameInstanceId", + gameInstanceId.toString()), + "lifecycleStatus", + "PREPARING", + "lifecycleEpoch", + 12, + "rowVersion", + 19)); + byte[] requestBinding = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + 11L, + expiryText, + participationId, + 7L, + launchRead, + activationRequestId, + preparingEvidence); + String requestDigest = "sha256:" + hash(requestBinding); + + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceKey); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_start_session_activation_protections", + "control_plane_request_id", + fixture.requestId(), + "account_world_participation_id", + participationId, + "account_world_participation_fence", + 7L, + "original_post_authorization_tuple", + tuple, + "account_redemption_projection", + projection, + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + 11L, + "original_lease_expires_at", + expiry, + "acquired_at", + acquiredAt, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "world_activation_request_id", + activationRequestId, + "game_session_launch_read_evidence", + launchRead, + "world_preparing_evidence", + preparingEvidence, + "capture_source_version", + 13L, + "capture_source_fence", + 17L, + "capture_sha256", + captureDigest, + "capture_reference_bytes", + captureReference, + "capture_reference_sha256", + captureDigest, + "operation_identity_bytes", + operationIdentity, + "operation_identity_digest", + operationDigest, + "request_binding_bytes", + requestBinding, + "request_binding_digest", + requestDigest); + var parent = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, " + + "acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE control_plane_request_id = ?", + fixture.requestId()); + UUID id = parent.get("activation_protection_id", UUID.class); + insert( + fixture.dsl(), + "account_start_session_activation_protection_sources", + "activation_protection_id", + id, + "source_key", + sourceKey, + "source_evidence", + sourceEvidenceBytes); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE operation_identity_digest = ?", + operationDigest); + UUID id = stored.get("activation_protection_id", UUID.class); + assertThat(id).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(stored.get("activation_protection_fence", Long.class)).isPositive(); + assertThat(stored.get("acquired_at", OffsetDateTime.class)).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protections " + + "SET acquired_at = acquired_at " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("immutable; terminal settlement is separate"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(" + + "ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + // This synthetic SQL receipt proves only that V1003 permits a source writer after an immutable + // terminal-shaped row is committed. It is not a typed receipt or authenticated World producer + // proof. The original Account lease is deliberately expired before this settlement insert. + OffsetDateTime retainedAcquiredAt = stored.get("acquired_at", OffsetDateTime.class); + long protectionFence = stored.get("activation_protection_fence", Long.class); + byte[] accountEvidenceBytes = + accountEvidence( + id, + protectionFence, + retainedAcquiredAt, + requestBinding, + captureReference, + sourceEvidenceBytes); + byte[] activationResultBytes = + activationResult(activationRequestId, preparingEvidence, "COMMITTED"); + + Map changedCapture = readJson(accountEvidenceBytes); + byte[] wrongCapture = bytes("substituted capture reference"); + changedCapture.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(wrongCapture)); + changedCapture.put("originalSourceCaptureReferenceSha256", hash(wrongCapture)); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedCapture), + activationResultBytes); + + Map changedRequest = readJson(accountEvidenceBytes); + changedRequest.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(bytes("{\"schema\":\"substituted-request/v1\"}"))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedRequest), + activationResultBytes); + + Map changedSources = readJson(accountEvidenceBytes); + changedSources.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(bytes("substituted source")))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedSources), + activationResultBytes); + + byte[] terminalBytes = + terminalBytes( + id, protectionFence, activationRequestId, accountEvidenceBytes, activationResultBytes); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + accountEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes))); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protection_settlements " + + "SET outcome = outcome WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "DELETE FROM account_start_session_activation_protection_settlements " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "TRUNCATE account_start_session_activation_protection_settlements"))) + .hasMessageContaining("activation settlement is immutable"); + + for (String guard : + new String[] { + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()" + }) { + String guardDefinition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", guard) + .get(0, String.class); + assertThat(guardDefinition) + .contains("account_ss_admission_assert_no_pending") + .contains("account_start_session_world_participations"); + } + String pendingProtectionDefinition = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_ss_admission_assert_no_pending(text[])'::regprocedure)") + .get(0, String.class); + assertThat(pendingProtectionDefinition) + .contains("account_start_session_admission_protection_sources") + .contains("account_ss_admission_is_settled") + .contains("account_start_session_activation_protection_settlements"); + } + + @Test + void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(60)); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + valid.requestBytes(), + valid.operationIdentityBytes(), + valid.operationIdentityDigest())); + + Map changedProjectionRequest = + JSON.readValue(valid.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + byte[] originalTuple = + Base64.getDecoder() + .decode( + (String) changedProjectionRequest.get("originalPostAuthorizationTupleBytesBase64")); + byte[] differentSpelling = + (" " + new String(originalTuple, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); + changedProjectionRequest.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(differentSpelling)); + byte[] changedProjection = jsonBytes(changedProjectionRequest); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + changedProjection, + valid.operationIdentityBytes(), + valid.operationIdentityDigest()))) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + + byte[] changedAttempt = + activationRequest(valid, UUID.randomUUID().toString(), valid.expiryText(), "PREPARING"); + assertCurrentnessRejected(fixture, changedAttempt, valid.operationIdentityBytes()); + + byte[] changedWorldState = + activationRequest(valid, valid.ownerAttemptId().toString(), valid.expiryText(), "ACTIVE"); + assertCurrentnessRejected(fixture, changedWorldState, valid.operationIdentityBytes()); + + Fixture expiredFixture = fixture(); + CurrentnessCase expired = currentnessCase(expiredFixture, Instant.now().minusSeconds(1)); + assertCurrentnessRejected( + expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + byte[] terminalBytes = + terminalBytes( + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + protectionId, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + protectionEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes)))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + } + + private static byte[] accountEvidence( + UUID protectionId, + long protectionFence, + OffsetDateTime acquiredAt, + byte[] requestBytes, + byte[] captureReference, + byte[] sourceEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-evidence/v1"); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(requestBytes)); + value.put("accountProtectionId", protectionId.toString()); + value.put("accountProtectionFence", Long.toString(protectionFence)); + value.put("acquiredAt", timestamp(acquiredAt)); + value.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReference)); + value.put("originalSourceCaptureReferenceSha256", hash(captureReference)); + value.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(sourceEvidence))); + return jsonBytes(value); + } + + private static byte[] accountEvidenceBytes(Map value) throws Exception { + return jsonBytes(value); + } + + private static byte[] activationResult( + UUID activationRequestId, byte[] preparingEvidence, String outcome) throws Exception { + Map preparing = readJson(preparingEvidence); + @SuppressWarnings("unchecked") + Map lifecycleRequest = (Map) preparing.get("request"); + lifecycleRequest.remove("readRequestId"); + Map activationRequest = new LinkedHashMap<>(); + activationRequest.put("schema", "world-canonical-instance-activation-request/v1"); + activationRequest.put("activationRequestId", activationRequestId.toString()); + activationRequest.put("preparingEvidence", preparing); + byte[] activationRequestBytes = jsonBytes(activationRequest); + + Map result = new LinkedHashMap<>(); + result.put("schema", "world-canonical-instance-activation-result/v1"); + result.put("activationRequestId", activationRequestId.toString()); + result.put("requestDigest", "sha256:" + hash(activationRequestBytes)); + result.put("requestBytesBase64", Base64.getEncoder().encodeToString(activationRequestBytes)); + result.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + result.put("outcome", outcome); + result.put("terminalCode", "COMMITTED".equals(outcome) ? null : "FENCED_ABORT"); + result.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(bytes("synthetic ACTIVE"))); + return jsonBytes(result); + } + + private static byte[] terminalBytes( + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + Map terminal = new LinkedHashMap<>(); + terminal.put("schema", "world-original-start-session-activation-terminal-evidence/v1"); + terminal.put("activationRequestId", activationRequestId.toString()); + terminal.put("accountProtectionId", protectionId.toString()); + terminal.put("accountProtectionFence", Long.toString(protectionFence)); + terminal.put("worldActivationFence", "29"); + terminal.put( + "accountProtectionEvidenceBytesBase64", + Base64.getEncoder().encodeToString(protectionEvidenceBytes)); + terminal.put( + "activationResultBytesBase64", Base64.getEncoder().encodeToString(activationResultBytes)); + terminal.put("activationResultSha256", hash(activationResultBytes)); + try { + return jsonBytes(terminal); + } catch (Exception impossible) { + throw new IllegalStateException("Synthetic terminal receipt must be canonical", impossible); + } + } + + private static Map readJson(byte[] bytes) throws Exception { + return JSON.readValue(bytes, new tools.jackson.core.type.TypeReference<>() {}); + } + + private static String timestamp(OffsetDateTime value) { + return DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(value.toInstant()); + } + + private static void assertCurrentnessRejected( + Fixture fixture, byte[] requestBytes, byte[] operationIdentityBytes) { + String operationDigest = "sha256:" + hash(operationIdentityBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + requestBytes, + operationIdentityBytes, + operationDigest))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + } + + private static CurrentnessCase currentnessCase(Fixture fixture, Instant originalLease) + throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID issuanceOperationId = UUID.randomUUID(); + long ownerFence = 11L; + long issuanceFence = 9L; + long sourceVersion = 13L; + long sourceFence = 17L; + String requestId = "original-activation/" + UUID.randomUUID(); + String fingerprint = "arfp/v1/activation-test/" + "a".repeat(64); + OffsetDateTime dbNow = + fixture.dsl().fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + Instant normalizedNow = dbNow.toInstant().truncatedTo(ChronoUnit.MICROS); + Instant normalizedLease = originalLease.truncatedTo(ChronoUnit.MICROS); + Instant issuedAt = normalizedNow.minusSeconds(10); + Instant redeemedAt = normalizedNow.minusSeconds(5); + Instant referenceExpiry = normalizedNow.plusSeconds(180); + Instant responseExpiry = normalizedNow.plusSeconds(220); + String expiryText = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(normalizedLease); + + byte[] preAuthorization = bytes("{}"); + Map bundleValue = + Map.of( + "issuanceOperationIdentity", + Map.of("issuanceOperationId", issuanceOperationId.toString())); + byte[] authorityBundle = jsonBytes(bundleValue); + byte[] tuple = + jsonBytes( + Map.of( + "controlPlaneRequestId", + requestId, + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + fingerprint, + "issuanceFence", + Long.toString(issuanceFence), + "authorityEvidenceBundle", + bundleValue)); + // Current-use integrity preserves the complete stipulated original tuple without scalarizing + // it. + byte[] projection = tuple.clone(); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + tenantId.toString(), + "2", + "17", + null, + null, + bytes("activation-source")); + String sourceKey = sourceEvidence.key(); + byte[] snapshot = + jsonBytes( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + java.util.List.of( + Base64.getEncoder().encodeToString(sourceEvidence.canonicalBytes())))); + byte[] captureReference = bytes("{}"); + String captureDigest = hash(captureReference); + String snapshotDigest = hash(snapshot); + byte[] attemptBytes = bytes("synthetic-current-original-attempt"); + String preparationInput = "{}"; + String preparationDigest = "sha256:" + hash(bytes(preparationInput)); + + byte[] worldPreparing = + jsonBytes( + Map.of( + "schema", + "world-canonical-instance-lifecycle-evidence/v1", + "request", + Map.of( + "controlPlaneRequestId", + requestId, + "targetNamespace", + "test", + "canonicalTenantId", + tenantId.toString(), + "canonicalGameInstanceId", + gameInstanceId.toString()), + "lifecycleStatus", + "PREPARING")); + byte[] launchRead = bytes("synthetic exact STARTING read"); + byte[] operationIdentity = bytes("activation operation identity"); + String operationDigest = "sha256:" + hash(operationIdentity); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceKey); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + accountId, + "tenant_uuid", + tenantId, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + issuanceFence, + "issuance_fence_source_version", + sourceVersion, + "captured_at", + OffsetDateTime.ofInstant( + normalizedNow.truncatedTo(ChronoUnit.MILLIS), ZoneOffset.UTC), + "snapshot_sha256", + snapshotDigest, + "canonical_snapshot_bytes", + snapshot, + "source_version", + sourceVersion, + "source_fence", + sourceFence, + "linearization", + "19", + "canonical_sha256", + captureDigest, + "canonical_capture_bytes", + captureReference); + insert( + fixture.dsl(), + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuanceOperationId, + "issuance_fence", + issuanceFence, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + Long.toString(sourceVersion), + "bundle_source_fence", + Long.toString(sourceFence), + "bundle_linearization", + "19", + "authority_evidence_bundle", + authorityBundle, + "authorization_reference_fingerprint", + fingerprint, + "encrypted_response_envelope", + bytes("synthetic response"), + "issued_at", + OffsetDateTime.ofInstant(issuedAt, ZoneOffset.UTC), + "reference_expires_at", + OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), + "response_envelope_expires_at", + OffsetDateTime.ofInstant(responseExpiry, ZoneOffset.UTC), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + ownerAttemptId, + "redemption_owner_fence", + ownerFence, + "redeemed_at", + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + "redemption_reference_fingerprint", + fingerprint, + "redemption_authority_evidence_bundle", + authorityBundle); + insert( + fixture.dsl(), + "account_start_session_world_participations", + "participation_id", + participationId, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "preparation_input_json", + preparationInput, + "preparation_input_digest", + preparationDigest); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + participationId, + "source_key", + sourceKey, + "source_evidence", + sourceEvidence.canonicalBytes()); + insert( + fixture.dsl(), + "account_start_session_world_original_attempt_evidence", + "participation_id", + participationId, + "target_namespace", + "test", + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "original_lease_expires_at", + OffsetDateTime.ofInstant(normalizedLease, ZoneOffset.UTC), + "original_response_bytes", + attemptBytes, + "original_response_digest", + "sha256:" + hash(attemptBytes)); + insert( + fixture.dsl(), + "account_start_session_world_participation_settlements", + "participation_id", + participationId, + "outcome", + "COMMITTED", + "world_execution_fence", + 3L, + "terminal_bytes", + bytes("synthetic committed preparation"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic committed preparation"))); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + byte[] requestBytes = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + ownerFence, + expiryText, + participationId, + fixture + .dsl() + .fetchSingle( + "SELECT participation_fence FROM account_start_session_world_participations " + + "WHERE participation_id = ?", + participationId) + .get("participation_fence", Long.class), + launchRead, + activationRequestId, + worldPreparing); + return new CurrentnessCase( + requestBytes, operationIdentity, operationDigest, ownerAttemptId, expiryText); + } + + private static byte[] activationRequest( + CurrentnessCase current, String ownerAttemptId, String expiry, String worldStatus) + throws Exception { + Map root = + JSON.readValue(current.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + root.put("gameSessionOwnerAttemptId", ownerAttemptId); + root.put("originalLeaseExpiresAt", expiry); + byte[] preparing = + Base64.getDecoder().decode((String) root.get("preparingEvidenceBytesBase64")); + Map world = + JSON.readValue(preparing, new tools.jackson.core.type.TypeReference<>() {}); + world.put("lifecycleStatus", worldStatus); + root.put("preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(jsonBytes(world))); + return jsonBytes(root); + } + + private static byte[] activationRequest( + byte[] tuple, + byte[] projection, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String expiry, + UUID participationId, + long participationFence, + byte[] launchRead, + UUID activationRequestId, + byte[] preparingEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-request/v1"); + value.put( + "originalPostAuthorizationTupleBytesBase64", Base64.getEncoder().encodeToString(tuple)); + value.put( + "accountRedemptionProjectionBytesBase64", Base64.getEncoder().encodeToString(projection)); + value.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + value.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(ownerFence)); + value.put("originalLeaseExpiresAt", expiry); + value.put("accountWorldParticipationId", participationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(participationFence)); + value.put( + "gameSessionLaunchReadEvidenceBytesBase64", Base64.getEncoder().encodeToString(launchRead)); + value.put("worldActivationRequestId", activationRequestId.toString()); + value.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + byte[] result = jsonBytes(value); + return result; + } + + private static byte[] jsonBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Fixture fixture() { + String schema = "ss_activation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + String requestId = "activation-test/" + UUID.randomUUID(); + return new Fixture(dsl, transaction, requestId); + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new java.util.LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) { + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + } + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record Fixture(DSLContext dsl, TransactionTemplate transaction, String requestId) {} + + private record CurrentnessCase( + byte[] requestBytes, + byte[] operationIdentityBytes, + String operationIdentityDigest, + UUID ownerAttemptId, + String expiryText) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..8792e629aa --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -0,0 +1,1442 @@ +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.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.util.PSQLException; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * SQL integrity and source-writer definitions. Upstream Account capture, redeemed authorization, + * World settlement and Game Session observation are explicitly stipulated with upstream triggers + * disabled. Current admission guards remain enabled for acquisition and all assertions. These + * fixtures are not genuine authenticated Account/World/Game Session producer or consumer proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionAdmissionProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + // Exact installed parent artifacts at Entity source 9526190049a86feef40cd616ec7b5eb931247e8b. + private static final Set PARENT_MIGRATION_SCRIPTS = + Set.of( + "V100__account_jwt_signer_materialization_readback.sql", + "V101__account_jwt_jwks_prepublication.sql", + "V103__account_jwt_readiness_probes.sql", + "V106__account_jwt_signer_promotion_lifecycle.sql", + "V107__account_jwt_readiness_single_delivery_claims.sql", + "V109__account_jwt_validator_inventory_snapshots.sql", + "V10__platform_fee.sql", + "V11__donation_flag.sql", + "V123__account_jwt_readiness_per_pod_closure.sql", + "V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql", + "V125__account_jwt_signer_promotion_receipt_binding.sql", + "V126.1__start_session_operator_response_envelope_erasure.sql", + "V126.2__account_control_ui_registry_cleanup_deadline.sql", + "V126.3__start_session_response_envelope_bounds.sql", + "V126__start_session_operator_authorization.sql", + "V12__virtual_currency.sql", + "V137.1__account_platform_restriction_lifecycle_consistency.sql", + "V137.2__account_platform_restriction_outbox_column_qualification.sql", + "V137.3__account_security_guard_source_row_type.sql", + "V137__account_platform_restriction_revision_receipts.sql", + "V13__creator_share.sql", + "V140__account_gameplay_admission_lease_operations.sql", + "V141__account_admission_unknown_decision_abort.sql", + "V142__account_admission_durable_commit_confirmation.sql", + "V143__account_global_pending_admission_fences.sql", + "V144__account_admission_original_ack_receipt.sql", + "V145__retire_experimental_admission_confirmation_writes.sql", + "V146__account_original_ack_pg18_fresh_insert.sql", + "V147__account_gameplay_delegation_issuance.sql", + "V148__account_auth_evidence_bundles.sql", + "V149__account_gameplay_delegation_encrypted_response.sql", + "V14__tenant_indexes.sql", + "V150__account_gameplay_delegation_committed_issuance.sql", + "V151__account_gameplay_token_identity_fences.sql", + "V152__account_gameplay_login_credential_request_binding.sql", + "V153__account_gameplay_delegation_decimal_source_versions.sql", + "V154__account_auth_evidence_checkpoint_key_count.sql", + "V155__account_auth_evidence_shared_issuer_guard.sql", + "V156__account_gameplay_commit_bundle_source_fence.sql", + "V157.1__account_gameplay_token_fence_truncate_guard.sql", + "V157__account_gameplay_authority_shared_issuer_guard.sql", + "V158__account_start_session_authority_captures.sql", + "V159__start_session_world_participation.sql", + "V15__account_tenant_membership.sql", + "V160.1__start_session_operator_bundle_source_fence.sql", + "V160__start_session_world_original_attempt_evidence.sql", + "V16__profile_presence_visibility.sql", + "V17__account_realm_access_grants.sql", + "V18__account_email_login_challenges.sql", + "V19__account_login_auth_modes.sql", + "V1__init.sql", + "V20__account_lifecycle_state.sql", + "V21__validate_account_lifecycle_state.sql", + "V22__canonicalize_account_emails.sql", + "V23__validate_account_email_canonical_check.sql", + "V24__account_credential_expiry_indexes.sql", + "V25__scope_profile_identity.sql", + "V26__global_registration_join_evidence.sql", + "V27__retain_join_connect_scopes.sql", + "V28__account_audit_delivery_backoff.sql", + "V29__account_identity_uuid_bridge.sql", + "V2__payment_tables.sql", + "V30__approved_legacy_tenant_associations.sql", + "V31__subscription_authority_generation.sql", + "V32__realm_grant_currentness.sql", + "V33__fresh_tenant_identity_associations.sql", + "V34__account_membership_pair_authority.sql", + "V35__canonical_uuid_membership_identity.sql", + "V36__account_auth_authority_generations.sql", + "V37__canonical_first_join_scope_and_intent.sql", + "V38__account_first_join_authority_outbox_and_roles.sql", + "V39__canonical_first_join_terminal_receipt.sql", + "V3__tenant_columns.sql", + "V40.1__retained_tenant_approval_payload_references.sql", + "V40__account_authority_source_baselines.sql", + "V4__roles_2fa.sql", + "V53__account_protected_demo_entitlements.sql", + "V5__payment_tenant_columns.sql", + "V6__password_reset_token.sql", + "V73__account_tenant_authority_source_bridge.sql", + "V74__account_global_role_source.sql", + "V75__draft_commit_authorization_fences.sql", + "V76__account_draft_required_owner_fence.sql", + "V77__account_password_reset_operation_receipts.sql", + "V78__account_logout_all_operation_receipts.sql", + "V79__account_security_state_operations.sql", + "V7__external_account.sql", + "V80__account_security_event_source_guard.sql", + "V81__account_platform_restriction_birth_sources.sql", + "V82__creator_membership_provenance.sql", + "V83__account_tenant_creation_bootstrap.sql", + "V84__individual_creator_party_sources.sql", + "V85__account_hosted_terms_acceptance_workflow.sql", + "V86__account_hosted_terms_environment_binding.sql", + "V87__account_control_ui_owner_source_guards.sql", + "V88__account_logout_all_pending_draft_source_changes.sql", + "V89__account_password_reset_pending_draft_source_changes.sql", + "V8__email_verification.sql", + "V90__account_control_ui_committed_issuance.sql", + "V91__account_selected_publication_authorization.sql", + "V92__account_publication_pre_freeze_order.sql", + "V93__account_selected_publication_settlement.sql", + "V94__selected_publication_inventory_v2.sql", + "V95__game_logic_intake_authorization.sql", + "V96__game_logic_intake_terminal_settlement.sql", + "V97__game_logic_intake_source_read_reservation.sql", + "V98__account_hosted_terms_disclosure_handoffs.sql", + "V99__account_jwt_signer_desired_state.sql", + "V9__payment_provider_id.sql", + "V1000__create_saga_schema.sql", + "V1001__saga_instance_table.sql", + "V1002__saga_step_table.sql"); + + @Test + void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGuards() { + String schema = "ss_fresh_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + actualParentFlyway(source, "classpath:db/migration", "classpath:db/migration/saga").migrate(); + actualParentFlyway(source, "classpath:db/migration", "classpath:db/migration/saga").validate(); + var dsl = DSL.using(source, SQLDialect.POSTGRES); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(113L); + assertThat( + dsl.fetchSingle( + "SELECT max(version::int) FROM flyway_schema_history_account_service WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1003); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", + schema) + .get(0, Long.class)) + .isZero(); + for (String signature : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_activation_assert_current(bytea,bytea,text,boolean)")) { + assertThat( + dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)) + .contains("issuanceOperationIdentity,issuanceOperationId"); + } + } + + @Test + void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesSourceProtections( + @TempDir Path parentMigrations) throws Exception { + var parent = fixture(60_000L, "160.1", false); + parent + .dsl() + .execute( + "ALTER TABLE flyway_schema_history RENAME TO flyway_schema_history_account_service"); + int copied = 0; + for (var resource : + new PathMatchingResourcePatternResolver() + .getResources("classpath*:db/migration/**/*.sql")) { + String filename = java.util.Objects.requireNonNull(resource.getFilename()); + if (!PARENT_MIGRATION_SCRIPTS.contains(filename)) continue; + try (var input = resource.getInputStream()) { + Files.copy(input, parentMigrations.resolve(filename)); + } + copied++; + } + assertThat(copied).isEqualTo(112); + actualParentFlyway(parent, "filesystem:" + parentMigrations).migrate(); + var checksums = + parent + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_account_service WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + assertThat(checksums).hasSize(112); + var capture = retainedPhysicalRows(parent, "account_start_session_authority_captures"); + + actualParentFlyway(parent, "classpath:db/migration", "classpath:db/migration/saga").migrate(); + actualParentFlyway(parent, "classpath:db/migration", "classpath:db/migration/saga").validate(); + + assertThat( + parent + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND installed_rank <= 112 ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(checksums); + assertThat(retainedPhysicalRows(parent, "account_start_session_authority_captures")) + .isEqualTo(capture); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND success") + .get(0, Long.class)) + .isEqualTo(113L); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT to_regclass('account_start_session_admission_protections')::TEXT") + .get(0, String.class)) + .isNotNull(); + } + + private static Flyway actualParentFlyway(Fixture fixture, String... locations) { + return actualParentFlyway(fixture.dataSource(), locations); + } + + private static Flyway actualParentFlyway(DriverManagerDataSource source, String... locations) { + return Flyway.configure() + .dataSource(source) + .schemas(source.getSchema()) + .defaultSchema(source.getSchema()) + .placeholders(Map.of("serviceSchema", source.getSchema())) + .locations(locations) + .table("flyway_schema_history_account_service") + .load(); + } + + @Test + void forwardMigrationAddsSourceProtectionsWithoutChangingRetainedCanonicalParentEvidence() { + Fixture parent = fixture(60_000L, "160.1", false); + // A passive non-authorizing signer baseline is explicitly stipulated, as are the upstream + // capture/World rows in this fixture. This does not establish authenticated producer proof. + parent + .transaction() + .executeWithoutResult( + status -> { + parent.dsl().execute("SET LOCAL session_replication_role = replica"); + parent + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode) " + + "VALUES ('test', 'test-cluster', 'test', 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK')"); + parent.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + List retainedTables = + List.of( + "account_jwt_signer_desired_states", + "account_draft_authorization_source_locks", + "account_start_session_authority_captures", + "account_start_session_operator_authorizations", + "account_start_session_world_participations", + "account_start_session_world_participation_sources", + "account_start_session_world_original_attempt_evidence", + "account_start_session_world_participation_settlements"); + Map beforeRows = new LinkedHashMap<>(); + Map beforeOids = new LinkedHashMap<>(); + for (String table : retainedTables) { + beforeRows.put(table, retainedPhysicalRows(parent, table)); + beforeOids.put( + table, + parent.dsl().fetchSingle("SELECT ?::regclass::oid::bigint", table).get(0, Long.class)); + } + List retainedFunctions = + List.of( + "account_start_session_world_participation_insert_guard()", + "account_start_session_operator_authorization_guard()", + "account_jwt_signer_promotion_insert_guard()"); + Map beforeDefinitions = new LinkedHashMap<>(); + for (String signature : retainedFunctions) { + beforeDefinitions.put( + signature, + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)); + beforeOids.put( + signature, + parent + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)); + } + var checksums = + parent + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank"); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT to_regclass('account_start_session_admission_protections')::TEXT") + .get(0, String.class)) + .isNull(); + Flyway.configure() + .dataSource(parent.dataSource()) + .schemas(parent.dataSource().getSchema()) + .defaultSchema(parent.dataSource().getSchema()) + .placeholders(Map.of("serviceSchema", parent.dataSource().getSchema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("1003")) + .load() + .migrate(); + for (String table : retainedTables) { + assertThat(retainedPhysicalRows(parent, table)).isEqualTo(beforeRows.get(table)); + assertThat( + parent.dsl().fetchSingle("SELECT ?::regclass::oid::bigint", table).get(0, Long.class)) + .isEqualTo(beforeOids.get(table)); + } + for (String signature : retainedFunctions) { + assertThat( + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)) + .isEqualTo(beforeDefinitions.get(signature)); + assertThat( + parent + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)) + .isEqualTo(beforeOids.get(signature)); + } + for (var row : checksums) { + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT checksum FROM flyway_schema_history WHERE success AND version = ?", + row.get("version", String.class)) + .get(0, Integer.class)) + .isEqualTo(row.get("checksum", Integer.class)); + } + for (String signature : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_activation_assert_current(bytea,bytea,text,boolean)")) { + String definition = + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class); + assertThat(definition) + .contains("issuanceOperationIdentity,issuanceOperationId") + .doesNotContain("'projectionSchemaId', 'accountStartSessionRedemptionProjection'"); + } + acquire(parent); + assertThat(parent.projection()).containsExactly(parent.tuple()); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT bundle_source_fence, issuance_fence FROM account_start_session_operator_authorizations WHERE control_plane_request_id = ?", + parent.requestId()) + .get("bundle_source_fence", String.class)) + .isEqualTo("13"); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT issuance_fence FROM account_start_session_operator_authorizations WHERE control_plane_request_id = ?", + parent.requestId()) + .get(0, Long.class)) + .isEqualTo(9L); + + Fixture scalar = fixture(60_000L, null, true); + assertThatThrownBy(() -> acquire(scalar)) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + } + + private static String retainedPhysicalRows(Fixture fixture, String table) { + return fixture + .dsl() + .fetchSingle( + "SELECT coalesce(jsonb_agg(value ORDER BY value::TEXT), '[]'::JSONB)::TEXT " + + "FROM (SELECT to_jsonb(original) || jsonb_build_object(" + + "'_xmin', original.xmin::TEXT, '_ctid', original.ctid::TEXT) AS value FROM " + + table + + " original) retained") + .get(0, String.class); + } + + @Test + void fullTupleDoesNotBypassIndependentOwnerIssuanceOperationBinding() { + Fixture fixture = fixture(); + // Stipulate a contradictory retained owner row to isolate this SQL integrity conjunct. + // The parent immutable writer remains enabled outside this deliberate corruption fixture. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThat(fixture.projection()).containsExactly(fixture.tuple()); + assertThatThrownBy(() -> acquire(fixture)) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { + Fixture fixture = fixture(); + for (String function : + List.of( + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()")) { + String definition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", function) + .get(0, String.class); + assertThat(definition) + .contains( + "account_ss_admission_assert_no_pending", + "account_start_session_world_participations") + // The actual published parent has the canonical World guard. Selected-owner source + // reservations remain a separate V130 receiving obligation, outside passive V165. + .doesNotContain("account_selected_owner_intake_source_read"); + } + String hold = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_control_ui_hold_required_sources(text[])'::regprocedure)") + .get(0, String.class); + assertThat(hold) + .contains( + "account_draft_authorization_sources", + "account_selected_publication_sources", + "account_game_logic_intake_sources", + "account_game_logic_intake_source_read_sources"); + } + + @Test + void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotReleaseIt() { + Fixture fixture = fixture(); + assertThat(fixture.expiry().getNano() % 1_000_000).isNotZero(); + acquire(fixture); + Long sequence = sequenceValue(fixture); + for (int retry = 0; retry < 2; retry++) { + var current = + fixture + .transaction() + .execute( + status -> + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request())); + assertThat(current.get("protection_id", UUID.class)).isEqualTo(fixture.protectionId()); + assertThat(current.get("request_binding_bytes", byte[].class)) + .containsExactly(fixture.request()); + OffsetDateTime retainedExpiry = + current.get("original_lease_expires_at", OffsetDateTime.class); + assertThat(retainedExpiry).isNotNull(); + assertThat(retainedExpiry.toInstant()).isEqualTo(fixture.expiry().toInstant()); + } + assertThat(sequenceValue(fixture)).isEqualTo(sequence); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT account_start_session_world_participation_is_settled(?)", + fixture.worldId()) + .get(0, Boolean.class)) + .isTrue(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void changedSubmillisecondOriginalExpiryCannotRecoverRetainedProtection() { + Fixture fixture = fixture(); + acquire(fixture); + var storedRowBefore = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + DateTimeFormatter expiryFormat = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + String originalExpiryText = expiryFormat.format(fixture.expiry().toInstant()); + String changedExpiryText = expiryFormat.format(fixture.expiry().plusNanos(1_000).toInstant()); + byte[] changedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(originalExpiryText, changedExpiryText) + .getBytes(StandardCharsets.UTF_8); + assertThat(changedRequest).isNotEqualTo(fixture.request()); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + changedRequest))) + .hasMessageContaining("Original admission recovery binding differs"); + var storedRowAfter = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + assertThat(storedRowAfter).isEqualTo(storedRowBefore); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void forgedWorldHoldDigestWithoutCanonicalPrefixCannotBecomeProtection() { + Fixture fixture = fixture(); + String holdText = new String(fixture.hold(), StandardCharsets.UTF_8); + String digestMarker = "\"holdBindingDigest\":\""; + int digestStart = holdText.indexOf(digestMarker) + digestMarker.length(); + int digestEnd = holdText.indexOf('"', digestStart); + String validDigest = holdText.substring(digestStart, digestEnd); + assertThat(validDigest).startsWith("sha256:"); + String forgedHoldText = + holdText.substring(0, digestStart) + + validDigest.substring("sha256:".length()) + + holdText.substring(digestEnd); + byte[] forgedHold = forgedHoldText.getBytes(StandardCharsets.UTF_8); + byte[] forgedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(base64(fixture.hold()), base64(forgedHold)) + .getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) + .hasMessageContaining("Admission hold identity differs from original instance and request"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void pendingAdmissionExcludesRealSourceChangeCompletionAndDisclosureDispatch() { + Fixture fixture = fixture(); + acquire(fixture); + UUID changeId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> { + insert( + fixture.dsl(), + "account_draft_authorization_source_changes", + "change_id", + changeId, + "binding", + bytes("change"), + "status", + "WAITING"); + insert( + fixture.dsl(), + "account_draft_authorization_changed_scopes", + "change_id", + changeId, + "source_key", + fixture.source().key()); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED', committed_at = clock_timestamp() WHERE change_id = ?", + changeId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + UUID handoffId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_hosted_terms_disclosure_handoffs", + "handoff_id", + handoffId, + "request_id", + UUID.randomUUID(), + "kind", + "CATALOG", + "source_key", + fixture.source().key(), + "predecessor_digest", + "sha256:" + "a".repeat(64), + "candidate_digest", + "sha256:" + "b".repeat(64), + "effective_at", + OffsetDateTime.now().plusDays(1), + "binding", + bytes("disclosure"), + "binding_digest", + "sha256:" + hash(bytes("disclosure")), + "status", + "PREPARED")); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void rawChangedCaptureAndIncompleteChildrenCannotBecomeProtection() { + Fixture changed = fixture(); + assertThatThrownBy( + () -> + changed + .transaction() + .executeWithoutResult(status -> insertProtection(changed, 99L))) + .hasMessageContaining("retained owner bindings"); + Fixture incomplete = fixture(); + assertThatThrownBy( + () -> + incomplete + .transaction() + .executeWithoutResult(status -> insertProtection(incomplete, 11L))) + .satisfies( + failure -> + assertDatabaseGuardFailure( + failure, + "Admission protection has incomplete or extra source children", + "23514")); + assertThat( + incomplete + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { + Fixture fixture = fixture(); + acquire(fixture); + for (String table : + List.of( + "account_start_session_admission_protections", + "account_start_session_admission_protection_sources")) { + assertThatThrownBy(() -> fixture.dsl().execute("DELETE FROM " + table)) + .hasMessageContaining("append-only"); + assertThatThrownBy(() -> fixture.dsl().execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("append-only"); + } + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protection_sources SET source_evidence = ?", + bytes("changed"))) + .hasMessageContaining("append-only"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", + fixture.protectionId(), + malformedSettlementBytes(), + "sha256:" + hash(malformedSettlementBytes()))) + .hasMessageContaining("not the closed envelope"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void expiredOriginalCannotRecoverEvenWhenRetainedIdentityAndSourcesRemain() { + Fixture fixture = fixture(); + acquire(fixture); + // Stipulate passage of the immutable original expiry without changing protection: + // rewriting the fixture row requires disabling the immutable upstream/new triggers. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protections SET original_lease_expires_at = date_trunc('milliseconds', clock_timestamp() - INTERVAL '1 second') WHERE protection_id = ?", + fixture.protectionId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()))) + .hasMessageContaining("not current"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void currentRecoveryRechecksDatabaseExpiryAfterTheCallerWaitsForOriginalCaptureLock() + throws Exception { + Fixture fixture = fixture(3_000L); + acquire(fixture); + var executor = Executors.newSingleThreadExecutor(); + CountDownLatch entered = new CountDownLatch(1); + try (Connection lock = fixture.dataSource().getConnection()) { + lock.setAutoCommit(false); + DSL.using(lock, SQLDialect.POSTGRES) + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + var waiting = + executor.submit( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + entered.countDown(); + // The currentness producer's original-capture lock can wait before the + // V165 + // boundary. V165 itself uses NOWAIT to avoid reversing source lock + // order. + fixture + .dsl() + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()); + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + long expiryDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class) + .equals(false) + && System.nanoTime() < expiryDeadline) { + Thread.sleep(20L); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class)) + .isTrue(); + assertThat(waiting.isDone()).isFalse(); + lock.commit(); + assertThatThrownBy(() -> waiting.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasStackTraceContaining("not current"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + private static void acquire(Fixture fixture) { + fixture + .transaction() + .executeWithoutResult( + status -> { + insertProtection(fixture, 11L); + insert( + fixture.dsl(), + "account_start_session_admission_protection_sources", + "protection_id", + fixture.protectionId(), + "source_key", + fixture.source().key(), + "source_evidence", + fixture.source().canonicalBytes()); + }); + } + + private static void insertProtection(Fixture fixture, long version) { + insertProtection(fixture, version, fixture.hold(), fixture.request()); + } + + private static void insertProtection( + Fixture fixture, long version, byte[] holdIdentity, byte[] request) { + insert( + fixture.dsl(), + "account_start_session_admission_protections", + "protection_id", + fixture.protectionId(), + "control_plane_request_id", + fixture.requestId(), + "original_post_authorization_tuple", + fixture.tuple(), + "account_redemption_projection", + fixture.projection(), + "game_session_owner_mutation_id", + fixture.mutationId(), + "game_session_owner_attempt_id", + fixture.attemptId(), + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + fixture.expiry(), + "account_world_participation_id", + fixture.worldId(), + "account_world_participation_fence", + 1L, + "target_namespace", + "test", + "canonical_tenant_id", + fixture.tenantId(), + "canonical_game_instance_id", + fixture.instanceId(), + "capture_source_version", + version, + "capture_source_fence", + 13L, + "capture_sha256", + hash(bytes("{}")), + "world_admission_hold_identity_bytes", + holdIdentity, + "request_binding_bytes", + request, + "request_binding_digest", + "sha256:" + hash(request)); + } + + private static Fixture fixture() { + return fixture(60_000L); + } + + private static Fixture fixture(long leaseMillis) { + return fixture(leaseMillis, null, false); + } + + private static Fixture fixture(long leaseMillis, String target, boolean scalarProjection) { + String schema = "ss_admission_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) migration.target(MigrationVersion.fromVersion(target)); + migration.load().migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + OffsetDateTime now = + dsl.fetchSingle( + "SELECT date_trunc('milliseconds', clock_timestamp()) + INTERVAL '123 microseconds'") + .get(0, OffsetDateTime.class); + OffsetDateTime capturedAt = now.truncatedTo(ChronoUnit.MILLIS); + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + UUID mutation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + UUID world = UUID.randomUUID(); + UUID issuance = UUID.randomUUID(); + String requestId = "original/" + UUID.randomUUID(); + SourceEvidence evidence = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "test-terms", "1", "1", null, null, bytes("terms")); + Map authorityBundle = + Map.of("issuanceOperationIdentity", Map.of("issuanceOperationId", issuance.toString())); + byte[] tuple = + json( + Map.of( + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "issuanceFence", + "9", + "authorityEvidenceBundle", + authorityBundle)); + // Upstream authority is explicitly stipulated; current SQL still requires exact tuple bytes. + byte[] projection = + scalarProjection + ? json( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "authorityEvidenceBundle", + authorityBundle, + "issuanceOperationId", + issuance.toString(), + "issuanceFence", + 9L)) + : tuple.clone(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + "test", + tenant, + "test-world", + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + instance, + UUID.randomUUID(), + 1L, + "separate-initial-admission-identity", + "b".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + byte[] hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()) + .canonicalBytes(); + OffsetDateTime expiry = now.plusNanos(leaseMillis * 1_000_000L); + byte[] request = + json( + Map.of( + "schema", + "account-start-session-admission-protection-request/v1", + "originalPostAuthorizationTupleBytesBase64", + base64(tuple), + "accountRedemptionProjectionBytesBase64", + base64(projection), + "gameSessionOwnerMutationId", + mutation.toString(), + "gameSessionOwnerAttemptId", + attempt.toString(), + "gameSessionOwnerFence", + "47", + "originalLeaseExpiresAt", + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(expiry.toInstant()), + "accountWorldParticipationId", + world.toString(), + "accountWorldParticipationFence", + "1", + "worldAdmissionHoldIdentityBytesBase64", + base64(hold))); + Fixture fixture = + new Fixture( + dsl, + transaction, + source, + UUID.randomUUID(), + requestId, + tenant, + instance, + mutation, + attempt, + world, + expiry, + evidence, + tuple, + projection, + hold, + request); + byte[] snapshot = + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + List.of(base64(evidence.canonicalBytes())))); + transaction.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + insert( + dsl, + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenant, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenant.toString()); + insert(dsl, "account_draft_authorization_source_locks", "source_key", evidence.key()); + insert( + dsl, + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + actor, + "tenant_uuid", + tenant, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + 9L, + "issuance_fence_source_version", + 1L, + "captured_at", + capturedAt, + "snapshot_sha256", + hash(snapshot), + "canonical_snapshot_bytes", + snapshot, + "source_version", + 11L, + "source_fence", + 13L, + "linearization", + "17", + "canonical_sha256", + hash(bytes("{}")), + "canonical_capture_bytes", + bytes("{}")); + insert( + dsl, + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuance, + "issuance_fence", + 9L, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + "11", + "bundle_source_fence", + "13", + "bundle_linearization", + "17", + "authority_evidence_bundle", + json(authorityBundle), + "authorization_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "encrypted_response_envelope", + bytes("synthetic"), + "issued_at", + now.minusSeconds(10), + "reference_expires_at", + now.plusSeconds(90), + "response_envelope_expires_at", + now.plusSeconds(120), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + attempt, + "redemption_owner_fence", + 47L, + "redeemed_at", + now.minusSeconds(5), + "redemption_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "redemption_authority_evidence_bundle", + json(authorityBundle)); + insert( + dsl, + "account_start_session_world_participations", + "participation_id", + world, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenant, + "canonical_game_instance_id", + instance, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "preparation_input_json", + "{}", + "preparation_input_digest", + "sha256:" + hash(bytes("{}"))); + insert( + dsl, + "account_start_session_world_participation_sources", + "participation_id", + world, + "source_key", + evidence.key(), + "source_evidence", + evidence.canonicalBytes()); + insert( + dsl, + "account_start_session_world_original_attempt_evidence", + "participation_id", + world, + "target_namespace", + "test", + "game_session_owner_mutation_id", + mutation, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + expiry, + "original_response_bytes", + bytes("synthetic-observation"), + "original_response_digest", + "sha256:" + hash(bytes("synthetic-observation"))); + insert( + dsl, + "account_start_session_world_participation_settlements", + "participation_id", + world, + "outcome", + "COMMITTED", + "world_execution_fence", + 1L, + "terminal_bytes", + bytes("synthetic-terminal"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic-terminal"))); + dsl.execute("SET LOCAL session_replication_role = origin"); + }); + return fixture; + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + try { + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } catch (RuntimeException failure) { + String sqlState = "unavailable"; + String constraint = "unavailable"; + StringBuilder causeTypes = new StringBuilder(); + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + int causeCount = 0; + while (cause != null && causeCount < 32 && visited.add(cause)) { + if (causeTypes.length() > 0) causeTypes.append("->"); + causeTypes.append(diagnosticIdentifier(cause.getClass().getSimpleName())); + causeCount++; + if (cause instanceof SQLException sqlFailure && sqlFailure.getSQLState() != null) { + sqlState = sqlFailure.getSQLState(); + } + if (cause instanceof PSQLException postgresFailure) { + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError != null && serverError.getConstraint() != null) { + constraint = serverError.getConstraint(); + } + } + cause = cause.getCause(); + } + if (cause != null) causeTypes.append("->truncated"); + System.err.printf( + "StartSession admission fixture insert failed: " + + "table=%s SQLSTATE=%s constraint=%s causeTypes=%s%n", + diagnosticIdentifier(table), + diagnosticIdentifier(sqlState), + diagnosticIdentifier(constraint), + causeTypes); + throw failure; + } + } + + private static String diagnosticIdentifier(String value) { + return value != null && value.matches("[A-Za-z0-9_]+") ? value : "unavailable"; + } + + private static Long sequenceValue(Fixture fixture) { + var sequence = + fixture + .dsl() + .fetchSingle( + "SELECT namespace.nspname AS schema_name, relation.relname AS sequence_name " + + "FROM pg_class relation " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE relation.oid = pg_get_serial_sequence(" + + "format('%I.%I', current_schema(), ?), ?)::regclass", + "account_start_session_admission_protections", "protection_fence"); + return fixture + .dsl() + .select(DSL.field(DSL.name("last_value"), Long.class)) + .from( + DSL.table( + DSL.name( + sequence.get("schema_name", String.class), + sequence.get("sequence_name", String.class)))) + .fetchSingle(0, Long.class); + } + + private static void assertDatabaseGuardFailure( + Throwable failure, String expectedMessage, String expectedSqlState) { + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + PSQLException databaseFailure = null; + while (cause != null && visited.add(cause)) { + if (cause instanceof PSQLException postgresFailure) { + databaseFailure = postgresFailure; + break; + } + cause = cause.getCause(); + } + assertThat((Throwable) databaseFailure) + .as("the rejected fixture write must fail at PostgreSQL's database guard") + .isNotNull(); + assertThat(databaseFailure.getSQLState()).isEqualTo(expectedSqlState); + assertThat(databaseFailure.getServerErrorMessage()).isNotNull(); + assertThat(databaseFailure.getServerErrorMessage().getMessage()).contains(expectedMessage); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] malformedSettlementBytes() { + return bytes( + "{\"canonicalAccountProtectionEvidenceBytesBase64\":\"\"," + + "\"canonicalGameSessionOwnerProofBytesBase64\":\"\"," + + "\"schema\":\"account-start-session-admission-protection-settlement/v2\"}"); + } + + private static byte[] json(Map value) { + return AccountControlUiAuthority.canonical(value); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String hash(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + UUID protectionId, + String requestId, + UUID tenantId, + UUID instanceId, + UUID mutationId, + UUID attemptId, + UUID worldId, + OffsetDateTime expiry, + SourceEvidence source, + byte[] tuple, + byte[] projection, + byte[] hold, + byte[] request) {} +} 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 62fef1910f..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 @@ -32,11 +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( - JooqEntityManagementRepositorySupport.ownerResolvedActorExists( - dsl, - ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, - ACTOR_ACTIVE_CONDITIONS.TENANT_ID)) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -64,11 +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( - JooqEntityManagementRepositorySupport.ownerResolvedActorExists( - dsl, - ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, - ACTOR_ACTIVE_CONDITIONS.TENANT_ID)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) @@ -77,8 +67,6 @@ public List findActiveForCharacter( } public ActorActiveCondition save(ActorActiveCondition entity) { - JooqEntityManagementRepositorySupport.requireOwnerResolvedActor( - dsl, entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_ACTIVE_CONDITIONS) @@ -99,34 +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( - JooqEntityManagementRepositorySupport.ownerResolvedActorExists( - dsl, - ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, - ACTOR_ACTIVE_CONDITIONS.TENANT_ID))) - .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; } @@ -137,12 +109,7 @@ public int deleteExpired(Instant now) { ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT .isNotNull() - .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now))) - .and( - JooqEntityManagementRepositorySupport.ownerResolvedActorExists( - dsl, - ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, - ACTOR_ACTIVE_CONDITIONS.TENANT_ID))) + .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now)))) .execute(); } 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 dbbe409d76..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 @@ -29,17 +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( - JooqEntityManagementRepositorySupport.ownerResolvedActorExists( - dsl, ACTOR_RESOURCE_STATES.CHARACTER_ID, ACTOR_RESOURCE_STATES.TENANT_ID))) + .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } public ActorResourceState save(ActorResourceState entity) { - JooqEntityManagementRepositorySupport.requireOwnerResolvedActor( - dsl, entity.getTenantId(), entity.getCharacterId()); if (entity.getId() == null) { Long id = dsl.insertInto(ACTOR_RESOURCE_STATES) @@ -59,31 +54,16 @@ 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( - JooqEntityManagementRepositorySupport.ownerResolvedActorExists( - dsl, - ACTOR_RESOURCE_STATES.CHARACTER_ID, - ACTOR_RESOURCE_STATES.TENANT_ID))) - .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; } 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 e8a0490329..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 @@ -5,7 +5,6 @@ import static net.firedevops.firemud.entitymanagement.jooq.Tables.ITEMS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.CharacterEquipmentEntry; import org.jooq.DSLContext; import org.jooq.Record; @@ -36,10 +35,7 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and( - CHARACTERS.ACTOR_IDENTITY_STATUS.eq( - ActorIdentityStatus.OWNER_RESOLVED.name())))); + .and(CHARACTERS.TENANT_ID.eq(tenantId)))); var content = dsl.select( CHARACTER_EQUIPMENT.CHARACTER_ID, @@ -72,10 +68,7 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and( - CHARACTERS.ACTOR_IDENTITY_STATUS.eq( - ActorIdentityStatus.OWNER_RESOLVED.name()))) + .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 f04b905db0..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,18 +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.ActorIdentityStatus; 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; @@ -29,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)) @@ -52,28 +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( - ActorIdentityStatus.OWNER_RESOLVED.name()))); - 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()) @@ -91,39 +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( - ActorIdentityStatus.OWNER_RESOLVED.name())))); - 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( - ActorIdentityStatus.OWNER_RESOLVED.name())))); - 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 40ea8dc05f..83f7402391 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 @@ -2,30 +2,146 @@ 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.ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES; import static net.firedevops.firemud.entitymanagement.jooq.Tables.INVENTORY; import static net.firedevops.firemud.entitymanagement.jooq.Tables.ITEMS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.InventoryEntry; import net.firedevops.firemud.entitymanagement.entity.InventoryKey; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshot; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotDigest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult.Outcome; +import org.jooq.Condition; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; +import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class CharacterRepository { + private static final Table ASSIGNMENT_OPERATIONS = + DSL.table(DSL.name("entity_preseeded_actor_assignment_operations")); + private static final Table TENANT_IDENTITIES = DSL.table(DSL.name("entity_tenant_identities")); + private static final Table ROSTER_SNAPSHOTS = + DSL.table(DSL.name("entity_canonical_gameplay_roster_snapshots")); + private static final Table ROSTER_SNAPSHOT_ACTORS = + DSL.table(DSL.name("entity_canonical_gameplay_roster_snapshot_actors")); + + private static final Field ASSIGNMENT_UUID = uuidField("assignment_uuid"); + private static final Field INTENT_DIGEST = stringField("intent_digest"); + private static final Field ACCOUNT_UUID = uuidField("account_uuid"); + private static final Field ACCOUNT_UUID_PROVENANCE = + stringField("account_uuid_provenance"); + private static final Field ACCOUNT_IDENTITY_SCHEMA_VERSION = + DSL.field(DSL.name("account_identity_schema_version"), Short.class); + private static final Field ACCOUNT_IDENTITY_TARGET_NAMESPACE = + stringField("account_identity_target_namespace"); + private static final Field SOURCE_ACCOUNT_ROW_ID = longField("source_account_row_id"); + private static final Field ELIGIBILITY = stringField("eligibility"); + private static final Field ELIGIBILITY_EVALUATED_AT = + DSL.field(DSL.name("eligibility_evaluated_at"), OffsetDateTime.class); + private static final Field MEMBERSHIP_AUTHORITY_GENERATION = + longField("membership_authority_generation"); + private static final Field ELIGIBILITY_EVIDENCE_DIGEST = + stringField("eligibility_evidence_digest"); + private static final Field ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST = + stringField("account_authority_snapshot_digest"); + private static final Field ACCOUNT_PURPOSE = stringField("account_purpose"); + private static final Field ACCOUNT_CURRENTNESS = stringField("account_currentness"); + private static final Field PUBLISHED_OWNER_PROOF_DIGEST = + stringField("published_owner_proof_digest"); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + stringField("published_release_bundle_ref"); + private static final Field TENANT_UUID = uuidField("tenant_uuid"); + private static final Field CANONICAL_TENANT_UUID = uuidField("canonical_tenant_uuid"); + private static final Field REALM_UUID = uuidField("realm_uuid"); + private static final Field WORLD_SLUG = stringField("world_slug"); + private static final Field REALM_SLUG = stringField("realm_slug"); + private static final Field GAME_INSTANCE_ID = stringField("game_instance_id"); + private static final Field CATALOG_REVISION = longField("catalog_revision"); + private static final Field CANONICAL_VERSION_UUID = uuidField("canonical_version_uuid"); + private static final Field PUBLICATION_EVIDENCE_FORMAT = + stringField("publication_evidence_format"); + private static final String CURRENT_PUBLICATION_EVIDENCE_FORMAT = "CANONICAL_UUID"; + private static final Field FROZEN_POLICY_DIGEST = stringField("frozen_policy_digest"); + private static final Field NAMESPACE_UUID = uuidField("playable_state_namespace_id"); + private static final Field PLAYABLE_STATE_SCOPE = stringField("playable_state_scope"); + private static final Field ENTRY_POLICY = stringField("entry_policy"); + private static final Field ACTOR_KIND = stringField("actor_kind"); + private static final Field DISPLAY_NAME = stringField("display_name"); + private static final Field ASSIGNMENT_STATUS = stringField("status"); + private static final Field ASSIGNED_CHARACTER_UUID = uuidField("character_uuid"); + private static final Field ASSIGNMENT_COMPLETED_AT = + DSL.field(DSL.name("completed_at"), OffsetDateTime.class); + private static final Field ENTITY_TENANT_ROW_ID = longField("entity_tenant_row_id"); + private static final Field ROSTER_SNAPSHOT_UUID = uuidField("snapshot_uuid"); + private static final Field ROSTER_SNAPSHOT_DIGEST = stringField("snapshot_digest"); + private static final Field ROSTER_ACCOUNT_UUID = uuidField("canonical_account_uuid"); + private static final Field ROSTER_TENANT_UUID = uuidField("tenant_uuid"); + private static final Field ROSTER_REALM_UUID = uuidField("realm_uuid"); + private static final Field ROSTER_WORLD_SLUG = stringField("world_slug"); + private static final Field ROSTER_REALM_SLUG = stringField("realm_slug"); + private static final Field ROSTER_GAME_INSTANCE_UUID = uuidField("game_instance_uuid"); + private static final Field ROSTER_CATALOG_REVISION = longField("catalog_revision"); + private static final Field ROSTER_CANONICAL_VERSION_UUID = + uuidField("canonical_version_uuid"); + private static final Field ROSTER_POINTER_VERSION = longField("pointer_version"); + private static final Field ROSTER_ACTIVE_WORLD_EPOCH = longField("active_world_epoch"); + private static final Field ROSTER_PUBLICATION_EVIDENCE_FORMAT = + stringField("publication_evidence_format"); + private static final String CURRENT_ROSTER_EVIDENCE_FORMAT = "CANONICAL_UUID_V2"; + private static final Field ROSTER_PUBLISHED_POLICY_DIGEST = + stringField("published_policy_digest"); + private static final Field ROSTER_PUBLISHED_RELEASE_REF = + stringField("published_release_bundle_ref"); + private static final Field ROSTER_POINTER_SNAPSHOT_DIGEST = + stringField("admission_pointer_snapshot_digest"); + private static final Field ROSTER_OWNER_PROOF_DIGEST = + stringField("published_owner_proof_digest"); + private static final Field ROSTER_NAMESPACE_UUID = + uuidField("playable_state_namespace_uuid"); + private static final Field ROSTER_PLAYABLE_SCOPE = stringField("playable_state_scope"); + private static final Field ROSTER_ENTRY_POLICY = stringField("entry_policy"); + private static final Field ROSTER_COUNT = DSL.field(DSL.name("roster_count"), Short.class); + private static final Field ROSTER_CONSTRUCTION_STATE = stringField("construction_state"); + private static final Field ROSTER_ORDINAL = + DSL.field(DSL.name("ordinal_position"), Short.class); + private static final Field ROSTER_CHARACTER_UUID = uuidField("character_uuid"); + private static final Field ROSTER_DISPLAY_NAME = stringField("display_name"); + private static final Field ROSTER_ACTOR_KIND = stringField("actor_kind"); + private final DSLContext dsl; public CharacterRepository(DSLContext dsl) { @@ -34,15 +150,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( - ActorIdentityStatus.OWNER_RESOLVED.name()))) - .fetchOne(this::toEntity); + dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity); if (character == null) { return Optional.empty(); } @@ -75,28 +183,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( - ActorIdentityStatus.OWNER_RESOLVED.name()))) - .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( - ActorIdentityStatus.OWNER_RESOLVED.name()))) + .where(CHARACTERS.ID.eq(id).and(CHARACTERS.TENANT_ID.eq(tenantId))) .fetchOne(this::toEntity)); } @@ -109,10 +202,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( - ActorIdentityStatus.OWNER_RESOLVED.name()))) + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey))) .fetchOne(this::toEntity)); } @@ -123,8 +213,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(ActorIdentityStatus.OWNER_RESOLVED.name())); + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)); long total = dsl.fetchCount(CHARACTERS, condition); var content = dsl.selectFrom(CHARACTERS) @@ -147,10 +236,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( - ActorIdentityStatus.OWNER_RESOLVED.name()))) + .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase()))) .limit(1) .fetchOne(this::toEntity)); } @@ -168,6 +254,993 @@ public long countQuarantinedByTenantId(Long tenantId) { .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.QUARANTINED.name()))); } + /** + * Atomically enrolls the owner-proven namespace, records one replay guard, and allocates the + * Entity-owned actor/account association after the protected assignment service authorizes the + * exact run-owned action and owner evidence. The committed actor is non-admitting; this + * repository operation has no direct RPC adapter and grants no PLAY authority. + */ + @Transactional + public PreseededActorAssignmentResult assignPreseededActor( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + String intentDigest) { + if (request == null + || evidence == null + || evidence.eligibility() != PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE + || evidence.entryPolicy() + != PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY + || evidence.accountPurpose() + != PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING + || evidence.accountCurrentness() + != PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION + || accountIdentityEvidence == null + || !request.assignmentUuid().equals(evidence.assignmentUuid()) + || !request.canonicalAccountUuid().equals(evidence.canonicalAccountUuid()) + || !request.expectedTarget().exactlyMatches(evidence) + || !evidence.assignmentUuid().equals(accountIdentityEvidence.requestId()) + || !evidence.canonicalAccountUuid().equals(accountIdentityEvidence.canonicalAccountId()) + || intentDigest == null + || !intentDigest.matches("[0-9a-f]{64}") + || !request.mutationIntentDigest().equals(intentDigest)) { + throw new IllegalArgumentException("Exact eligible pre-seeded assignment proof is required"); + } + + var insertedGuard = + insertAssignmentGuard(request, evidence, accountIdentityEvidence, intentDigest); + if (insertedGuard == null) { + return replayOrConflict(request, evidence, intentDigest); + } + + enrollNamespace(evidence); + long entityTenantRowId = requireEntityTenantRow(evidence.canonicalTenantUuid()); + if (hasOwnerResolvedAccountNamespace(evidence)) { + completeWithoutActor(evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, intentDigest); + } + UUID characterUuid = UUID.randomUUID(); + + if (!insertOwnerResolvedCharacter( + request, + evidence, + accountIdentityEvidence.sourceAccountRowId(), + entityTenantRowId, + characterUuid)) { + // The partial unique index is the final guard if another writer does not use this row lock. + // Persist the deterministic loser result after confirming the account/namespace slot won. + if (!hasOwnerResolvedAccountNamespace(evidence)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACTOR_INSERT_FAILED"); + } + completeWithoutActor(evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, intentDigest); + } + completeWithActor(evidence.assignmentUuid(), characterUuid); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.ASSIGNED, characterUuid, intentDigest); + } + + private Record insertAssignmentGuard( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + String intentDigest) { + return dsl.insertInto(ASSIGNMENT_OPERATIONS) + .set(ASSIGNMENT_UUID, evidence.assignmentUuid()) + .set(INTENT_DIGEST, intentDigest) + .set(ACCOUNT_UUID, evidence.canonicalAccountUuid()) + .set(ACCOUNT_UUID_PROVENANCE, accountIdentityEvidence.accountUuidProvenance()) + .set(ACCOUNT_IDENTITY_SCHEMA_VERSION, (short) accountIdentityEvidence.schemaVersion()) + .set(ACCOUNT_IDENTITY_TARGET_NAMESPACE, accountIdentityEvidence.targetNamespace()) + .set(SOURCE_ACCOUNT_ROW_ID, accountIdentityEvidence.sourceAccountRowId()) + .set(ELIGIBILITY, evidence.eligibility().name()) + .set( + ELIGIBILITY_EVALUATED_AT, + OffsetDateTime.ofInstant(evidence.eligibilityEvaluatedAt(), ZoneOffset.UTC)) + .set(MEMBERSHIP_AUTHORITY_GENERATION, evidence.membershipAuthorityGeneration()) + .set(ELIGIBILITY_EVIDENCE_DIGEST, evidence.eligibilityEvidenceDigest()) + .set(ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST, evidence.accountAuthoritySnapshotDigest()) + .set(ACCOUNT_PURPOSE, evidence.accountPurpose().name()) + .set(ACCOUNT_CURRENTNESS, evidence.accountCurrentness().name()) + .set(PUBLISHED_OWNER_PROOF_DIGEST, evidence.publishedOwnerProofDigest()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, evidence.publishedReleaseBundleRef()) + .set(TENANT_UUID, evidence.canonicalTenantUuid()) + .set(REALM_UUID, evidence.realmUuid()) + .set(WORLD_SLUG, evidence.worldSlug()) + .set(REALM_SLUG, evidence.realmSlug()) + .set(GAME_INSTANCE_ID, evidence.gameInstanceId()) + .set(CATALOG_REVISION, evidence.catalogRevision()) + .set(CANONICAL_VERSION_UUID, evidence.canonicalVersionUuid()) + .set(PUBLICATION_EVIDENCE_FORMAT, CURRENT_PUBLICATION_EVIDENCE_FORMAT) + .set(FROZEN_POLICY_DIGEST, evidence.frozenPolicyDigest()) + .set(NAMESPACE_UUID, evidence.playableStateNamespaceId()) + .set(PLAYABLE_STATE_SCOPE, evidence.playableStateScope().name()) + .set(ENTRY_POLICY, evidence.entryPolicy().name()) + .set(ACTOR_KIND, request.corePayload().actorKind().name()) + .set(DISPLAY_NAME, request.corePayload().displayName()) + .set(ASSIGNMENT_STATUS, "PENDING") + .onConflict(ASSIGNMENT_UUID) + .doNothing() + .returning(ASSIGNMENT_UUID) + .fetchOne(); + } + + private PreseededActorAssignmentResult replayOrConflict( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + String requestedDigest) { + Record stored = + dsl.select( + INTENT_DIGEST, + ACCOUNT_UUID, + ASSIGNMENT_COMPLETED_AT, + TENANT_UUID, + REALM_UUID, + WORLD_SLUG, + REALM_SLUG, + GAME_INSTANCE_ID, + CATALOG_REVISION, + CANONICAL_VERSION_UUID, + PUBLICATION_EVIDENCE_FORMAT, + FROZEN_POLICY_DIGEST, + NAMESPACE_UUID, + PLAYABLE_STATE_SCOPE, + ENTRY_POLICY, + ACTOR_KIND, + DISPLAY_NAME, + ASSIGNMENT_STATUS, + ASSIGNED_CHARACTER_UUID, + PUBLISHED_RELEASE_BUNDLE_REF) + .from(ASSIGNMENT_OPERATIONS) + .where(ASSIGNMENT_UUID.eq(evidence.assignmentUuid())) + .forUpdate() + .fetchOne(); + if (stored == null) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_REPLAY_GUARD_UNAVAILABLE"); + } + if (!CURRENT_PUBLICATION_EVIDENCE_FORMAT.equals(stored.get(PUBLICATION_EVIDENCE_FORMAT))) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_LEGACY_PUBLICATION_EVIDENCE"); + } + if (!requestedDigest.equals(stored.get(INTENT_DIGEST))) { + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, requestedDigest); + } + requireSameStoredIntent(stored, request, evidence); + + String status = stored.get(ASSIGNMENT_STATUS); + UUID characterUuid = stored.get(ASSIGNED_CHARACTER_UUID); + OffsetDateTime completedAt = stored.get(ASSIGNMENT_COMPLETED_AT); + if ("IDEMPOTENCY_CONFLICT".equals(status) && characterUuid == null && completedAt != null) { + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, requestedDigest); + } + if ("ASSIGNED".equals(status) && characterUuid != null && completedAt != null) { + requireStoredAssignedActor(evidence, characterUuid); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.ASSIGNED, characterUuid, requestedDigest); + } + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_REPLAY_RESULT_INCOMPLETE"); + } + + private void requireSameStoredIntent( + Record stored, + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence) { + boolean sameIntent = + evidence.canonicalAccountUuid().equals(stored.get(ACCOUNT_UUID)) + && evidence.canonicalTenantUuid().equals(stored.get(TENANT_UUID)) + && evidence.realmUuid().equals(stored.get(REALM_UUID)) + && evidence.worldSlug().equals(stored.get(WORLD_SLUG)) + && evidence.realmSlug().equals(stored.get(REALM_SLUG)) + && evidence.gameInstanceId().equals(stored.get(GAME_INSTANCE_ID)) + && evidence.catalogRevision() == stored.get(CATALOG_REVISION) + && evidence.canonicalVersionUuid().equals(stored.get(CANONICAL_VERSION_UUID)) + && evidence.frozenPolicyDigest().equals(stored.get(FROZEN_POLICY_DIGEST)) + && evidence.playableStateNamespaceId().equals(stored.get(NAMESPACE_UUID)) + && evidence.playableStateScope().name().equals(stored.get(PLAYABLE_STATE_SCOPE)) + && evidence.entryPolicy().name().equals(stored.get(ENTRY_POLICY)) + && evidence.publishedReleaseBundleRef().equals(stored.get(PUBLISHED_RELEASE_BUNDLE_REF)) + && request.corePayload().actorKind().name().equals(stored.get(ACTOR_KIND)) + && request.corePayload().displayName().equals(stored.get(DISPLAY_NAME)); + if (!sameIntent) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_STORED_INTENT_MISMATCH"); + } + } + + /** Returns only an exact committed operation whose PLAYER row remains owner-resolved. */ + @Transactional(readOnly = true) + public Optional readPreseededActorAssignmentReceipt( + PreseededActorAssignmentReceiptRequest request) { + Record operation = + dsl.select( + ASSIGNMENT_UUID, + INTENT_DIGEST, + ACCOUNT_UUID, + ACCOUNT_UUID_PROVENANCE, + ACCOUNT_IDENTITY_SCHEMA_VERSION, + ACCOUNT_IDENTITY_TARGET_NAMESPACE, + SOURCE_ACCOUNT_ROW_ID, + ELIGIBILITY, + ELIGIBILITY_EVALUATED_AT, + MEMBERSHIP_AUTHORITY_GENERATION, + ELIGIBILITY_EVIDENCE_DIGEST, + ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST, + ACCOUNT_PURPOSE, + ACCOUNT_CURRENTNESS, + PUBLISHED_OWNER_PROOF_DIGEST, + PUBLISHED_RELEASE_BUNDLE_REF, + TENANT_UUID, + REALM_UUID, + WORLD_SLUG, + REALM_SLUG, + GAME_INSTANCE_ID, + CATALOG_REVISION, + CANONICAL_VERSION_UUID, + PUBLICATION_EVIDENCE_FORMAT, + FROZEN_POLICY_DIGEST, + NAMESPACE_UUID, + PLAYABLE_STATE_SCOPE, + ENTRY_POLICY, + ACTOR_KIND, + ASSIGNMENT_STATUS, + ASSIGNED_CHARACTER_UUID, + DISPLAY_NAME, + ASSIGNMENT_COMPLETED_AT) + .from(ASSIGNMENT_OPERATIONS) + .where(ASSIGNMENT_UUID.eq(request.assignmentUuid())) + .fetchOne(); + if (operation == null + || !request.canonicalAccountUuid().equals(operation.get(ACCOUNT_UUID)) + || operation.get(ACCOUNT_UUID_PROVENANCE) == null + || operation.get(ACCOUNT_UUID_PROVENANCE).isBlank() + || operation.get(ACCOUNT_IDENTITY_SCHEMA_VERSION) == null + || operation.get(ACCOUNT_IDENTITY_TARGET_NAMESPACE) == null + || operation.get(SOURCE_ACCOUNT_ROW_ID) == null + || operation.get(TENANT_UUID) == null + || operation.get(REALM_UUID) == null + || operation.get(WORLD_SLUG) == null + || operation.get(REALM_SLUG) == null + || operation.get(GAME_INSTANCE_ID) == null + || operation.get(CATALOG_REVISION) == null + || !CURRENT_PUBLICATION_EVIDENCE_FORMAT.equals(operation.get(PUBLICATION_EVIDENCE_FORMAT)) + || operation.get(CANONICAL_VERSION_UUID) == null + || operation.get(FROZEN_POLICY_DIGEST) == null + || operation.get(NAMESPACE_UUID) == null + || operation.get(PUBLISHED_RELEASE_BUNDLE_REF) == null + || operation.get(PLAYABLE_STATE_SCOPE) == null + || operation.get(DISPLAY_NAME) == null + || !"ELIGIBLE".equals(operation.get(ELIGIBILITY)) + || !request.intentDigest().equals(operation.get(INTENT_DIGEST)) + || !"PLAYER".equals(operation.get(ACTOR_KIND)) + || !"ASSIGNED".equals(operation.get(ASSIGNMENT_STATUS)) + || operation.get(ASSIGNMENT_COMPLETED_AT) == null + || !request.characterUuid().equals(operation.get(ASSIGNED_CHARACTER_UUID))) { + return Optional.empty(); + } + + Record actor = + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_ID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, + CHARACTERS.NAME) + .from(CHARACTERS) + .where(CHARACTERS.CHARACTER_UUID.eq(request.characterUuid())) + .fetchOne(); + if (actor == null + || !request.canonicalAccountUuid().equals(actor.get(CHARACTERS.ACCOUNT_UUID)) + || !Objects.equals(operation.get(SOURCE_ACCOUNT_ROW_ID), actor.get(CHARACTERS.ACCOUNT_ID)) + || !Objects.equals(operation.get(TENANT_UUID), actor.get(CHARACTERS.TENANT_UUID)) + || !Objects.equals( + operation.get(NAMESPACE_UUID), actor.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID)) + || !Objects.equals( + operation.get(PLAYABLE_STATE_SCOPE), actor.get(CHARACTERS.PLAYABLE_STATE_SCOPE)) + || !ActorIdentityStatus.OWNER_RESOLVED + .name() + .equals(actor.get(CHARACTERS.ACTOR_IDENTITY_STATUS)) + || actor.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) != null + || !Objects.equals(operation.get(DISPLAY_NAME), actor.get(CHARACTERS.NAME))) { + return Optional.empty(); + } + + try { + var target = + new PreseededActorAssignmentExpectedTarget( + operation.get(TENANT_UUID), + operation.get(REALM_UUID), + operation.get(WORLD_SLUG), + operation.get(REALM_SLUG), + operation.get(GAME_INSTANCE_ID), + operation.get(CATALOG_REVISION), + operation.get(CANONICAL_VERSION_UUID), + operation.get(FROZEN_POLICY_DIGEST), + operation.get(NAMESPACE_UUID), + operation.get(PUBLISHED_RELEASE_BUNDLE_REF), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf( + operation.get(PLAYABLE_STATE_SCOPE))); + if (!request.expectedTarget().equals(target)) { + return Optional.empty(); + } + OffsetDateTime evaluatedAt = operation.get(ELIGIBILITY_EVALUATED_AT); + String evidenceDigest = operation.get(ELIGIBILITY_EVIDENCE_DIGEST); + String authorityDigest = operation.get(ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST); + String purpose = operation.get(ACCOUNT_PURPOSE); + String currentness = operation.get(ACCOUNT_CURRENTNESS); + String ownerProofDigest = operation.get(PUBLISHED_OWNER_PROOF_DIGEST); + String releaseRef = operation.get(PUBLISHED_RELEASE_BUNDLE_REF); + String entryPolicy = operation.get(ENTRY_POLICY); + Long generation = operation.get(MEMBERSHIP_AUTHORITY_GENERATION); + if (evaluatedAt == null + || generation == null + || generation <= 0 + || evidenceDigest == null + || authorityDigest == null + || ownerProofDigest == null + || releaseRef == null + || purpose == null + || currentness == null + || !"PRESEEDED_ACTOR_STAGING".equals(purpose) + || !"CURRENT_AT_REVALIDATION".equals(currentness) + || !"PRESEEDED_ONLY".equals(entryPolicy)) { + return Optional.empty(); + } + return Optional.of( + new PreseededActorAssignmentReceipt( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.characterUuid(), + request.intentDigest(), + target, + new net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload( + net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload + .ActorKind.valueOf(operation.get(ACTOR_KIND)), + operation.get(DISPLAY_NAME)), + operation.get(ACCOUNT_IDENTITY_SCHEMA_VERSION).intValue(), + operation.get(ACCOUNT_IDENTITY_TARGET_NAMESPACE), + operation.get(SOURCE_ACCOUNT_ROW_ID), + operation.get(ACCOUNT_UUID_PROVENANCE), + PreseededActorAssignmentOwnerEvidence.Eligibility.valueOf(operation.get(ELIGIBILITY)), + evaluatedAt.toInstant(), + generation, + evidenceDigest, + authorityDigest, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.valueOf(purpose), + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.valueOf(currentness), + ownerProofDigest, + releaseRef, + entryPolicy, + operation.get(ASSIGNMENT_STATUS))); + } catch (IllegalArgumentException invalidStoredReceipt) { + return Optional.empty(); + } + } + + /** + * Resolves one historical assignment for an exact selected actor and immutable target. Current + * owner counters are independently checked before this method is called; the persisted owner + * proof digest must still match that owner-resolved target. Zero or multiple matches disclose no + * assignment reference. + */ + @Transactional(readOnly = true) + public Optional readSelectedPreseededActorAssignmentReceipt( + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + PreseededActorAssignmentExpectedTarget expectedTarget, + String publishedOwnerProofDigest) { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(selectedCharacterUuid, "selectedCharacterUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + if (publishedOwnerProofDigest == null || !publishedOwnerProofDigest.matches("[0-9a-f]{64}")) { + return Optional.empty(); + } + + List matchingOperations = + dsl.select(ASSIGNMENT_UUID, INTENT_DIGEST) + .from(ASSIGNMENT_OPERATIONS) + .where( + ACCOUNT_UUID + .eq(canonicalAccountUuid) + .and(ASSIGNED_CHARACTER_UUID.eq(selectedCharacterUuid)) + .and(TENANT_UUID.eq(expectedTarget.canonicalTenantUuid())) + .and(REALM_UUID.eq(expectedTarget.realmUuid())) + .and(WORLD_SLUG.eq(expectedTarget.worldSlug())) + .and(REALM_SLUG.eq(expectedTarget.realmSlug())) + .and(GAME_INSTANCE_ID.eq(expectedTarget.gameInstanceId())) + .and(CATALOG_REVISION.eq(expectedTarget.catalogRevision())) + .and(CANONICAL_VERSION_UUID.eq(expectedTarget.canonicalVersionUuid())) + .and(FROZEN_POLICY_DIGEST.eq(expectedTarget.frozenPolicyDigest())) + .and(NAMESPACE_UUID.eq(expectedTarget.playableStateNamespaceId())) + .and(PLAYABLE_STATE_SCOPE.eq(expectedTarget.playableStateScope().name())) + .and( + PUBLISHED_RELEASE_BUNDLE_REF.eq(expectedTarget.publishedReleaseBundleRef())) + .and(PUBLISHED_OWNER_PROOF_DIGEST.eq(publishedOwnerProofDigest)) + .and(ENTRY_POLICY.eq("PRESEEDED_ONLY")) + .and(ACTOR_KIND.eq("PLAYER")) + .and(ASSIGNMENT_STATUS.eq("ASSIGNED")) + .and(ASSIGNMENT_COMPLETED_AT.isNotNull())) + .limit(2) + .fetch(); + Optional uniqueOperation = onlyOneAssignmentMatch(matchingOperations); + if (uniqueOperation.isEmpty()) { + return Optional.empty(); + } + + Record operation = uniqueOperation.orElseThrow(); + UUID assignmentUuid = operation.get(ASSIGNMENT_UUID); + String intentDigest = operation.get(INTENT_DIGEST); + if (assignmentUuid == null || intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + return Optional.empty(); + } + Optional receipt = + readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + canonicalAccountUuid, + selectedCharacterUuid, + intentDigest, + expectedTarget)); + if (receipt.isEmpty() + || !publishedOwnerProofDigest.equals(receipt.orElseThrow().publishedOwnerProofDigest())) { + return Optional.empty(); + } + return receipt; + } + + static Optional onlyOneAssignmentMatch(List matchingOperations) { + if (matchingOperations == null || matchingOperations.size() != 1) { + return Optional.empty(); + } + return Optional.ofNullable(matchingOperations.get(0)); + } + + /** + * Locks the immutable assignment and its current actor row before returning the exact receipt. + * Callers use this only inside the same writable transaction that records an applicability hold, + * so actor changes either win first and invalidate the receipt or observe the durable hold. + */ + @Transactional + public Optional lockCurrentPreseededActorAssignmentReceipt( + UUID assignmentUuid, UUID canonicalAccountUuid, UUID characterUuid, String intentDigest) { + if (!org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Pre-seeded placement receipt locking requires the writable hold transaction"); + } + Record operation = + dsl.select( + INTENT_DIGEST, + ACCOUNT_UUID, + TENANT_UUID, + REALM_UUID, + WORLD_SLUG, + REALM_SLUG, + GAME_INSTANCE_ID, + CATALOG_REVISION, + CANONICAL_VERSION_UUID, + FROZEN_POLICY_DIGEST, + NAMESPACE_UUID, + PLAYABLE_STATE_SCOPE, + PUBLISHED_RELEASE_BUNDLE_REF, + ASSIGNED_CHARACTER_UUID) + .from(ASSIGNMENT_OPERATIONS) + .where(ASSIGNMENT_UUID.eq(assignmentUuid)) + .forUpdate() + .fetchOne(); + if (operation == null + || !canonicalAccountUuid.equals(operation.get(ACCOUNT_UUID)) + || !characterUuid.equals(operation.get(ASSIGNED_CHARACTER_UUID)) + || !intentDigest.equals(operation.get(INTENT_DIGEST))) { + return Optional.empty(); + } + Record actor = + dsl.select(CHARACTERS.CHARACTER_UUID) + .from(CHARACTERS) + .where(CHARACTERS.CHARACTER_UUID.eq(characterUuid)) + .forUpdate() + .fetchOne(); + if (actor == null) { + return Optional.empty(); + } + try { + var target = + new PreseededActorAssignmentExpectedTarget( + operation.get(TENANT_UUID), + operation.get(REALM_UUID), + operation.get(WORLD_SLUG), + operation.get(REALM_SLUG), + operation.get(GAME_INSTANCE_ID), + operation.get(CATALOG_REVISION), + operation.get(CANONICAL_VERSION_UUID), + operation.get(FROZEN_POLICY_DIGEST), + operation.get(NAMESPACE_UUID), + operation.get(PUBLISHED_RELEASE_BUNDLE_REF), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf( + operation.get(PLAYABLE_STATE_SCOPE))); + return readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, canonicalAccountUuid, characterUuid, intentDigest, target)); + } catch (IllegalArgumentException invalidStoredTarget) { + return Optional.empty(); + } + } + + private void enrollNamespace(PreseededActorAssignmentOwnerEvidence evidence) { + dsl.insertInto(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .set(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, evidence.canonicalTenantUuid()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID, + evidence.playableStateNamespaceId()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE, + evidence.playableStateScope().name()) + .onConflict( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID) + .doNothing() + .execute(); + + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(evidence.canonicalTenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + evidence.playableStateNamespaceId()))) + .forUpdate() + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + if (!evidence.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_NAMESPACE_SCOPE_MISMATCH"); + } + } + + private long requireEntityTenantRow(UUID tenantUuid) { + dsl.insertInto(TENANT_IDENTITIES) + .set(CANONICAL_TENANT_UUID, tenantUuid) + .onConflict(CANONICAL_TENANT_UUID) + .doNothing() + .execute(); + Long rowId = + dsl.select(ENTITY_TENANT_ROW_ID) + .from(TENANT_IDENTITIES) + .where(CANONICAL_TENANT_UUID.eq(tenantUuid)) + .forUpdate() + .fetchOne(ENTITY_TENANT_ROW_ID); + if (rowId == null || rowId <= 0L) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ENTITY_TENANT_MAPPING_UNAVAILABLE"); + } + return rowId; + } + + private boolean hasOwnerResolvedAccountNamespace(PreseededActorAssignmentOwnerEvidence evidence) { + UUID existingActor = + dsl.select(CHARACTERS.CHARACTER_UUID) + .from(CHARACTERS) + .where( + CHARACTERS + .TENANT_UUID + .eq(evidence.canonicalTenantUuid()) + .and(CHARACTERS.ACCOUNT_UUID.eq(evidence.canonicalAccountUuid())) + .and( + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq( + evidence.playableStateNamespaceId())) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) + .limit(1) + .forUpdate() + .fetchOne(CHARACTERS.CHARACTER_UUID); + return existingActor != null; + } + + private boolean insertOwnerResolvedCharacter( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + long sourceAccountRowId, + long entityTenantRowId, + UUID characterUuid) { + Long characterRowId = + dsl.insertInto(CHARACTERS) + .set(CHARACTERS.CHARACTER_UUID, characterUuid) + .set(CHARACTERS.ACCOUNT_UUID, evidence.canonicalAccountUuid()) + .set(CHARACTERS.TENANT_UUID, evidence.canonicalTenantUuid()) + .set(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, evidence.playableStateNamespaceId()) + .set(CHARACTERS.PLAYABLE_STATE_SCOPE, evidence.playableStateScope().name()) + .set(CHARACTERS.ACTOR_IDENTITY_STATUS, ActorIdentityStatus.OWNER_RESOLVED.name()) + .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, (String) null) + .set(CHARACTERS.ACCOUNT_ID, sourceAccountRowId) + .set(CHARACTERS.TENANT_ID, entityTenantRowId) + .set(CHARACTERS.PLAYABLE_STATE_KEY, evidence.playableStateNamespaceId().toString()) + .set(CHARACTERS.NAME, request.corePayload().displayName()) + .onConflictDoNothing() + .returningResult(CHARACTERS.ID) + .fetchOne(CHARACTERS.ID); + return characterRowId != null; + } + + private void completeWithActor(UUID assignmentUuid, UUID characterUuid) { + int updated = + dsl.update(ASSIGNMENT_OPERATIONS) + .set(ASSIGNMENT_STATUS, "ASSIGNED") + .set(ASSIGNED_CHARACTER_UUID, characterUuid) + .set(ASSIGNMENT_COMPLETED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where(ASSIGNMENT_UUID.eq(assignmentUuid).and(ASSIGNMENT_STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OPERATION_COMPLETION_FAILED"); + } + } + + private void completeWithoutActor(UUID assignmentUuid, Outcome outcome) { + if (outcome != Outcome.IDEMPOTENCY_CONFLICT) { + throw new IllegalArgumentException("Only terminal no-actor outcomes can omit a character"); + } + int updated = + dsl.update(ASSIGNMENT_OPERATIONS) + .set(ASSIGNMENT_STATUS, outcome.name()) + .set(ASSIGNMENT_COMPLETED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where(ASSIGNMENT_UUID.eq(assignmentUuid).and(ASSIGNMENT_STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OPERATION_COMPLETION_FAILED"); + } + } + + private void requireStoredAssignedActor( + PreseededActorAssignmentOwnerEvidence evidence, UUID characterUuid) { + Record actor = + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS) + .from(CHARACTERS) + .where(CHARACTERS.CHARACTER_UUID.eq(characterUuid)) + .fetchOne(); + if (actor == null + || !evidence.canonicalAccountUuid().equals(actor.get(CHARACTERS.ACCOUNT_UUID)) + || !evidence.canonicalTenantUuid().equals(actor.get(CHARACTERS.TENANT_UUID)) + || !evidence + .playableStateNamespaceId() + .equals(actor.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID)) + || !evidence.playableStateScope().name().equals(actor.get(CHARACTERS.PLAYABLE_STATE_SCOPE)) + || !ActorIdentityStatus.OWNER_RESOLVED + .name() + .equals(actor.get(CHARACTERS.ACTOR_IDENTITY_STATUS))) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACTOR_PROVENANCE_MISMATCH"); + } + } + + /** + * Captures an ordered roster only from fresh owner-resolved actor rows, then persists and reads + * back its immutable target-bound snapshot. This lookup never uses legacy numeric actor fields. + */ + @Transactional + public CanonicalGameplayRosterSnapshot captureCanonicalGameplayRosterSnapshot( + CanonicalGameplayRosterReadRequest request, + CanonicalGameplayRosterOwnerEvidence ownerEvidence) { + if (request == null + || ownerEvidence == null + || !request.requestUuid().equals(ownerEvidence.requestUuid()) + || !request.canonicalAccountUuid().equals(ownerEvidence.canonicalAccountUuid()) + || !request.expectedTarget().equals(ownerEvidence.target()) + || ownerEvidence.target().entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new IllegalArgumentException("Exact PRESEEDED_ONLY owner evidence is required"); + } + + CanonicalGameplayRosterTarget target = ownerEvidence.target(); + lockCanonicalRosterNamespace(target); + requireEntityTenantRow(target.tenantUuid()); + + List currentActors = + readCurrentCanonicalRoster(request.canonicalAccountUuid(), target); + String digest = + CanonicalGameplayRosterSnapshotDigest.compute( + request.canonicalAccountUuid(), target, currentActors); + UUID proposedSnapshotUuid = UUID.randomUUID(); + UUID insertedSnapshotUuid = + dsl.insertInto(ROSTER_SNAPSHOTS) + .set(ROSTER_SNAPSHOT_UUID, proposedSnapshotUuid) + .set(ROSTER_SNAPSHOT_DIGEST, digest) + .set(ROSTER_ACCOUNT_UUID, request.canonicalAccountUuid()) + .set(ROSTER_TENANT_UUID, target.tenantUuid()) + .set(ROSTER_REALM_UUID, target.realmUuid()) + .set(ROSTER_WORLD_SLUG, target.worldSlug()) + .set(ROSTER_REALM_SLUG, target.realmSlug()) + .set(ROSTER_GAME_INSTANCE_UUID, target.gameInstanceUuid()) + .set(ROSTER_CATALOG_REVISION, target.catalogRevision()) + .set(ROSTER_CANONICAL_VERSION_UUID, target.canonicalVersionUuid()) + .set(ROSTER_POINTER_VERSION, target.pointerVersion()) + .set(ROSTER_ACTIVE_WORLD_EPOCH, target.activeWorldEpoch()) + .set(ROSTER_PUBLICATION_EVIDENCE_FORMAT, CURRENT_ROSTER_EVIDENCE_FORMAT) + .set(ROSTER_PUBLISHED_POLICY_DIGEST, target.publishedPolicyDigest()) + .set(ROSTER_PUBLISHED_RELEASE_REF, target.publishedReleaseBundleRef()) + .set(ROSTER_POINTER_SNAPSHOT_DIGEST, target.admissionPointerSnapshotDigest()) + .set(ROSTER_OWNER_PROOF_DIGEST, target.publishedOwnerProofDigest()) + .set(ROSTER_NAMESPACE_UUID, target.playableStateNamespaceId()) + .set(ROSTER_PLAYABLE_SCOPE, target.playableStateScope().name()) + .set(ROSTER_ENTRY_POLICY, target.entryPolicy().name()) + .set(ROSTER_COUNT, (short) currentActors.size()) + .set(ROSTER_CONSTRUCTION_STATE, "BUILDING") + .onConflict(ROSTER_SNAPSHOT_DIGEST) + .doNothing() + .returningResult(ROSTER_SNAPSHOT_UUID) + .fetchOne(ROSTER_SNAPSHOT_UUID); + + if (insertedSnapshotUuid != null) { + for (int index = 0; index < currentActors.size(); index++) { + CanonicalGameplayRosterActor actor = currentActors.get(index); + dsl.insertInto(ROSTER_SNAPSHOT_ACTORS) + .set(ROSTER_SNAPSHOT_UUID, insertedSnapshotUuid) + .set(ROSTER_ORDINAL, (short) index) + .set(ROSTER_CHARACTER_UUID, actor.characterUuid()) + .set(ROSTER_DISPLAY_NAME, actor.displayName()) + .set(ROSTER_ACTOR_KIND, "PLAYER") + .execute(); + } + int sealed = + dsl.update(ROSTER_SNAPSHOTS) + .set(ROSTER_CONSTRUCTION_STATE, "SEALED") + .where( + ROSTER_SNAPSHOT_UUID + .eq(insertedSnapshotUuid) + .and(ROSTER_CONSTRUCTION_STATE.eq("BUILDING"))) + .execute(); + if (sealed != 1) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_SEAL_FAILED"); + } + } + + return readBackCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), target, currentActors, digest, null); + } + + /** + * Reads back a previously sealed snapshot only when it still exactly describes the current + * owner-resolved roster. This never captures or creates a snapshot. + */ + @Transactional + public CanonicalGameplayRosterSnapshot readCurrentCanonicalGameplayRosterSnapshot( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterSnapshotReference expectedSnapshot) { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(expectedSnapshot, "expectedSnapshot"); + if (expectedTarget.entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new IllegalArgumentException("PRESEEDED_ONLY target is required"); + } + + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(expectedTarget.tenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + expectedTarget.playableStateNamespaceId()))) + .forShare() + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + if (!expectedTarget.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); + } + + List currentActors = + readCurrentCanonicalRoster(canonicalAccountUuid, expectedTarget); + String currentDigest = + CanonicalGameplayRosterSnapshotDigest.compute( + canonicalAccountUuid, expectedTarget, currentActors); + if (!expectedSnapshot.snapshotDigest().equals(currentDigest)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE"); + } + return readBackCanonicalGameplayRosterSnapshot( + canonicalAccountUuid, + expectedTarget, + currentActors, + currentDigest, + expectedSnapshot.snapshotUuid()); + } + + private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) { + dsl.insertInto(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .set(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, target.tenantUuid()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID, + target.playableStateNamespaceId()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE, + target.playableStateScope().name()) + .onConflict( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID) + .doNothing() + .execute(); + + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(target.tenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + target.playableStateNamespaceId()))) + .forUpdate() + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + if (!target.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); + } + } + + private List readCurrentCanonicalRoster( + UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + List actors = + dsl.select(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME) + .from(CHARACTERS) + .where( + CHARACTERS + .ACCOUNT_UUID + .eq(canonicalAccountUuid) + .and(CHARACTERS.TENANT_UUID.eq(target.tenantUuid())) + .and( + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq( + target.playableStateNamespaceId())) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(target.playableStateScope().name())) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name())) + .and(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON.isNull())) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .limit(CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE + 1) + .forShare() + .fetch( + row -> + new CanonicalGameplayRosterActor( + row.get(CHARACTERS.CHARACTER_UUID), row.get(CHARACTERS.NAME))); + if (actors.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); + } + return actors; + } + + private CanonicalGameplayRosterSnapshot readBackCanonicalGameplayRosterSnapshot( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + List expectedActors, + String expectedDigest, + UUID expectedSnapshotUuid) { + Condition snapshotCondition = ROSTER_SNAPSHOT_DIGEST.eq(expectedDigest); + if (expectedSnapshotUuid != null) { + snapshotCondition = snapshotCondition.and(ROSTER_SNAPSHOT_UUID.eq(expectedSnapshotUuid)); + } + Record stored = + dsl.select( + ROSTER_SNAPSHOT_UUID, + ROSTER_SNAPSHOT_DIGEST, + ROSTER_ACCOUNT_UUID, + ROSTER_TENANT_UUID, + ROSTER_REALM_UUID, + ROSTER_WORLD_SLUG, + ROSTER_REALM_SLUG, + ROSTER_GAME_INSTANCE_UUID, + ROSTER_CATALOG_REVISION, + ROSTER_CANONICAL_VERSION_UUID, + ROSTER_POINTER_VERSION, + ROSTER_ACTIVE_WORLD_EPOCH, + ROSTER_PUBLICATION_EVIDENCE_FORMAT, + ROSTER_PUBLISHED_POLICY_DIGEST, + ROSTER_PUBLISHED_RELEASE_REF, + ROSTER_POINTER_SNAPSHOT_DIGEST, + ROSTER_OWNER_PROOF_DIGEST, + ROSTER_NAMESPACE_UUID, + ROSTER_PLAYABLE_SCOPE, + ROSTER_ENTRY_POLICY, + ROSTER_COUNT, + ROSTER_CONSTRUCTION_STATE) + .from(ROSTER_SNAPSHOTS) + .where(snapshotCondition) + .forShare() + .fetchOne(); + if (stored == null + || !"SEALED".equals(stored.get(ROSTER_CONSTRUCTION_STATE)) + || !CURRENT_ROSTER_EVIDENCE_FORMAT.equals(stored.get(ROSTER_PUBLICATION_EVIDENCE_FORMAT))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_UNAVAILABLE"); + } + + CanonicalGameplayRosterTarget storedTarget = + new CanonicalGameplayRosterTarget( + stored.get(ROSTER_TENANT_UUID), + stored.get(ROSTER_REALM_UUID), + stored.get(ROSTER_WORLD_SLUG), + stored.get(ROSTER_REALM_SLUG), + stored.get(ROSTER_GAME_INSTANCE_UUID), + stored.get(ROSTER_CATALOG_REVISION), + stored.get(ROSTER_POINTER_VERSION), + stored.get(ROSTER_ACTIVE_WORLD_EPOCH), + stored.get(ROSTER_CANONICAL_VERSION_UUID), + stored.get(ROSTER_PUBLISHED_POLICY_DIGEST), + stored.get(ROSTER_PUBLISHED_RELEASE_REF), + stored.get(ROSTER_POINTER_SNAPSHOT_DIGEST), + stored.get(ROSTER_OWNER_PROOF_DIGEST), + stored.get(ROSTER_NAMESPACE_UUID), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf( + stored.get(ROSTER_PLAYABLE_SCOPE)), + net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .valueOf(stored.get(ROSTER_ENTRY_POLICY))); + + List storedActorRows = + dsl.select(ROSTER_ORDINAL, ROSTER_CHARACTER_UUID, ROSTER_DISPLAY_NAME, ROSTER_ACTOR_KIND) + .from(ROSTER_SNAPSHOT_ACTORS) + .where(ROSTER_SNAPSHOT_UUID.eq(stored.get(ROSTER_SNAPSHOT_UUID))) + .orderBy(ROSTER_ORDINAL.asc()) + .fetch(); + List storedActors = new ArrayList<>(storedActorRows.size()); + for (int index = 0; index < storedActorRows.size(); index++) { + Record row = storedActorRows.get(index); + Short ordinal = row.get(ROSTER_ORDINAL); + if (ordinal == null || ordinal != index || !"PLAYER".equals(row.get(ROSTER_ACTOR_KIND))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_ORDER_INVALID"); + } + storedActors.add( + new CanonicalGameplayRosterActor( + row.get(ROSTER_CHARACTER_UUID), row.get(ROSTER_DISPLAY_NAME))); + } + + Short storedCount = stored.get(ROSTER_COUNT); + UUID storedSnapshotUuid = stored.get(ROSTER_SNAPSHOT_UUID); + if (storedSnapshotUuid == null + || (expectedSnapshotUuid != null && !expectedSnapshotUuid.equals(storedSnapshotUuid)) + || !expectedDigest.equals(stored.get(ROSTER_SNAPSHOT_DIGEST)) + || !canonicalAccountUuid.equals(stored.get(ROSTER_ACCOUNT_UUID)) + || storedCount == null + || storedCount != storedActors.size() + || !expectedTarget.equals(storedTarget) + || !expectedActors.equals(storedActors) + || !expectedDigest.equals( + CanonicalGameplayRosterSnapshotDigest.compute( + canonicalAccountUuid, storedTarget, storedActors))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_MISMATCH"); + } + + if (!expectedActors.equals(readCurrentCanonicalRoster(canonicalAccountUuid, expectedTarget))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_CHANGED_DURING_READ"); + } + return new CanonicalGameplayRosterSnapshot( + canonicalAccountUuid, storedSnapshotUuid, expectedDigest, storedTarget, storedActors); + } + + private static Field uuidField(String name) { + return DSL.field(DSL.name(name), UUID.class); + } + + private static Field stringField(String name) { + return DSL.field(DSL.name(name), String.class); + } + + private static Field longField(String name) { + return DSL.field(DSL.name(name), Long.class); + } + public Character save(Character entity) { if (entity.getId() == null) { UUID characterUuid = UUID.randomUUID(); @@ -193,37 +1266,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( - ActorIdentityStatus.OWNER_RESOLVED.name()))) - .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(); } @@ -261,11 +1324,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 diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java index e094c0f26f..9a780b595c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java @@ -1,10 +1,7 @@ package net.firedevops.firemud.entitymanagement.repository; -import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; - import java.util.List; import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.CharacterEquipmentEntry; import net.firedevops.firemud.entitymanagement.entity.CharacterEquipmentKey; @@ -17,10 +14,6 @@ import net.firedevops.firemud.entitymanagement.entity.ItemStackCompatibilityMode; import net.firedevops.firemud.entitymanagement.entity.RoomGroundInventoryEntry; import net.firedevops.firemud.entitymanagement.entity.RoomGroundInventoryKey; -import org.jooq.Condition; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; @@ -28,37 +21,6 @@ final class JooqEntityManagementRepositorySupport { private JooqEntityManagementRepositorySupport() {} - static Condition ownerResolvedActorExists( - DSLContext dsl, Field characterField, Field tenantField) { - return DSL.exists( - dsl.selectOne() - .from(CHARACTERS) - .where( - CHARACTERS - .ID - .eq(characterField) - .and(CHARACTERS.TENANT_ID.eq(tenantField)) - .and( - CHARACTERS.ACTOR_IDENTITY_STATUS.eq( - ActorIdentityStatus.OWNER_RESOLVED.name())))); - } - - static void requireOwnerResolvedActor(DSLContext dsl, 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( - ActorIdentityStatus.OWNER_RESOLVED.name()))); - if (ownerResolvedCount != 1) { - throw new IllegalStateException("ACTOR_IDENTITY_NOT_OWNER_RESOLVED"); - } - } - static Page page(List content, Pageable pageable, long total) { if (pageable == null || pageable.isUnpaged()) { return new PageImpl<>(content); 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/CanonicalGameplayRosterActor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java new file mode 100644 index 0000000000..f08f38fe00 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java @@ -0,0 +1,21 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Persisted primary controllable actor returned by canonical roster discovery. */ +public record CanonicalGameplayRosterActor(UUID characterUuid, String displayName) { + public CanonicalGameplayRosterActor { + Objects.requireNonNull(characterUuid, "characterUuid"); + if (characterUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("characterUuid must be non-nil"); + } + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.codePointCount(0, displayName.length()) > 100 + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("displayName is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java new file mode 100644 index 0000000000..85e435da02 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** Published entry policies represented at the canonical roster boundary. */ +public enum CanonicalGameplayRosterEntryPolicy { + UNSPECIFIED, + PLAYER_CREATED, + PRESEEDED_ONLY, + AUTO_PROVISIONED +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java new file mode 100644 index 0000000000..00487bfc3d --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** Parsed unsigned scope carried by the authenticated, allowlisted gameplay workload. */ +public record CanonicalGameplayRosterExecutionContext( + UUID accountUuid, + UUID tenantUuid, + UUID playableStateNamespaceUuid, + UUID gameInstanceUuid, + UUID characterUuid, + UUID sessionUuid, + UUID realmUuid, + UUID requestUuid, + PlayableStateScope playableStateScope) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterExecutionContext { + requireNonNil(accountUuid, "accountUuid"); + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(playableStateNamespaceUuid, "playableStateNamespaceUuid"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + if (characterUuid != null) { + requireNonNil(characterUuid, "characterUuid"); + } + requireNonNil(sessionUuid, "sessionUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireNonNil(requestUuid, "requestUuid"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope == PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED + || playableStateScope == PlayableStateScope.UNRECOGNIZED) { + throw new IllegalArgumentException("playableStateScope is required"); + } + } + + public void requireTargetBinding( + UUID expectedRequestUuid, UUID expectedAccountUuid, CanonicalGameplayRosterTarget target) { + Objects.requireNonNull(target, "target"); + if (!requestUuid.equals(expectedRequestUuid) + || !accountUuid.equals(expectedAccountUuid) + || !tenantUuid.equals(target.tenantUuid()) + || !realmUuid.equals(target.realmUuid()) + || !playableStateNamespaceUuid.equals(target.playableStateNamespaceId()) + || !gameInstanceUuid.equals(target.gameInstanceUuid()) + || playableStateScope != target.playableStateScope()) { + throw new IllegalArgumentException("Player execution context does not match exact target"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java new file mode 100644 index 0000000000..faa7ce7666 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java @@ -0,0 +1,19 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; + +/** Live owner-resolved target evidence; it is not actor admission or runtime authorization. */ +public record CanonicalGameplayRosterOwnerEvidence( + UUID requestUuid, + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget target, + Instant resolvedAt) { + public CanonicalGameplayRosterOwnerEvidence { + Objects.requireNonNull(requestUuid, "requestUuid"); + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(resolvedAt, "resolvedAt"); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java new file mode 100644 index 0000000000..018e78d756 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** + * Resolves current Game Session owner evidence independently of the caller's expected target. + * + *

A production implementation must bind the exact Account UUID to canonical tenant, realm, + * active instance, namespace/scope, published PRESEEDED_ONLY policy, release/catalog version, + * admission-pointer evidence, and exact positive {@code pointerVersion} and {@code + * activeWorldEpoch} counters. It must reread those owners for every request; counters cannot be + * inferred from digests, defaults, or numeric identifiers. Cached assertions and caller-selected + * scope are not authority. Roster discovery remains non-admitting. + */ +@FunctionalInterface +public interface CanonicalGameplayRosterOwnerEvidencePort { + CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( + CanonicalGameplayRosterReadRequest request); + + final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("CANONICAL_GAMEPLAY_ROSTER_OWNER_EVIDENCE_UNAVAILABLE"); + } + + public OwnerEvidenceUnavailableException(Throwable cause) { + super("CANONICAL_GAMEPLAY_ROSTER_OWNER_EVIDENCE_UNAVAILABLE", cause); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java new file mode 100644 index 0000000000..155cd2ea03 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact-account canonical roster lookup with an independently checked target precondition. */ +public record CanonicalGameplayRosterReadRequest( + UUID requestUuid, + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterExecutionContext playerExecutionContext) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterReadRequest { + requireNonNil(requestUuid, "requestUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(playerExecutionContext, "playerExecutionContext") + .requireTargetBinding(requestUuid, canonicalAccountUuid, expectedTarget); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java new file mode 100644 index 0000000000..e55145745d --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact selected actor lookup precondition for a non-admitting PRESEEDED assignment read. */ +public record CanonicalGameplayRosterSelectedAssignmentReadRequest( + UUID requestUuid, + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterSnapshotReference expectedSnapshot, + CanonicalGameplayRosterExecutionContext playerExecutionContext) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterSelectedAssignmentReadRequest { + requireNonNil(requestUuid, "requestUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(selectedCharacterUuid, "selectedCharacterUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(expectedSnapshot, "expectedSnapshot"); + Objects.requireNonNull(playerExecutionContext, "playerExecutionContext") + .requireTargetBinding(requestUuid, canonicalAccountUuid, expectedTarget); + if (!selectedCharacterUuid.equals(playerExecutionContext.characterUuid())) { + throw new IllegalArgumentException( + "playerExecutionContext.character_id must equal selectedCharacterUuid"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java new file mode 100644 index 0000000000..6519e8befb --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Minimal historical assignment reference returned for one exact selected actor and target. */ +public record CanonicalGameplayRosterSelectedAssignmentReference( + UUID requestUuid, + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + CanonicalGameplayRosterTarget target, + CanonicalGameplayRosterSnapshotReference snapshot, + UUID assignmentUuid, + String intentDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterSelectedAssignmentReference { + requireNonNil(requestUuid, "requestUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(selectedCharacterUuid, "selectedCharacterUuid"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(snapshot, "snapshot"); + requireNonNil(assignmentUuid, "assignmentUuid"); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("intentDigest must be lowercase SHA-256 hex"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java new file mode 100644 index 0000000000..b31dc3e8a6 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Non-admitting read of the exact committed assignment for a selected PRESEEDED actor. */ +public final class CanonicalGameplayRosterSelectedAssignmentService { + private final CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort; + private final CharacterRepository characterRepository; + + public CanonicalGameplayRosterSelectedAssignmentService( + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + this.ownerEvidencePort = Objects.requireNonNull(ownerEvidencePort, "ownerEvidencePort"); + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public CanonicalGameplayRosterSelectedAssignmentReference read( + CanonicalGameplayRosterSelectedAssignmentReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requireSupportedTarget(request.expectedTarget()); + + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + CanonicalGameplayRosterOwnerEvidence evidence = + ownerEvidencePort.resolveCurrentTarget(ownerRequest); + if (evidence == null) { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + } + requireSupportedTarget(evidence.target()); + if (!request.requestUuid().equals(evidence.requestUuid()) + || !request.canonicalAccountUuid().equals(evidence.canonicalAccountUuid()) + || !request.expectedTarget().equals(evidence.target())) { + throw new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + + var snapshot = + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot()); + long selectedOccurrences = + snapshot.actors().stream() + .filter(actor -> request.selectedCharacterUuid().equals(actor.characterUuid())) + .count(); + if (selectedOccurrences != 1L) { + throw new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_NOT_IN_EXPECTED_SNAPSHOT"); + } + + PreseededActorAssignmentExpectedTarget expectedAssignmentTarget = + expectedAssignmentTarget(evidence.target()); + PreseededActorAssignmentReceipt receipt = + characterRepository + .readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + expectedAssignmentTarget, + evidence.target().publishedOwnerProofDigest()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_UNAVAILABLE")); + + if (!request.canonicalAccountUuid().equals(receipt.canonicalAccountUuid()) + || !request.selectedCharacterUuid().equals(receipt.characterUuid()) + || !request + .expectedTarget() + .publishedOwnerProofDigest() + .equals(receipt.publishedOwnerProofDigest()) + || !expectedAssignmentTarget.equals(receipt.target())) { + throw new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_RECEIPT_MISMATCH"); + } + + return new CanonicalGameplayRosterSelectedAssignmentReference( + request.requestUuid(), + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + request.expectedTarget(), + request.expectedSnapshot(), + receipt.assignmentUuid(), + receipt.intentDigest()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } + } + + private static void requireSupportedTarget(CanonicalGameplayRosterTarget target) { + if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY + || target.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + throw new UnsupportedOperationException("SELECTED_PRESEEDED_ASSIGNMENT_TARGET_UNSUPPORTED"); + } + } + + private static PreseededActorAssignmentExpectedTarget expectedAssignmentTarget( + CanonicalGameplayRosterTarget target) { + return new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope()); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java new file mode 100644 index 0000000000..9a05fce123 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Non-admitting PRESEEDED_ONLY roster discovery over persisted, owner-resolved actors. */ +public final class CanonicalGameplayRosterService { + private final CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort; + private final CharacterRepository characterRepository; + + public CanonicalGameplayRosterService( + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + this.ownerEvidencePort = Objects.requireNonNull(ownerEvidencePort, "ownerEvidencePort"); + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public CanonicalGameplayRosterSnapshot read(CanonicalGameplayRosterReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requirePreseededOnly(request.expectedTarget()); + if (request.playerExecutionContext().characterUuid() != null) { + throw new IllegalArgumentException("Roster discovery must not select a character"); + } + + CanonicalGameplayRosterOwnerEvidence evidence = ownerEvidencePort.resolveCurrentTarget(request); + if (evidence == null) { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + } + requirePreseededOnly(evidence.target()); + if (!request.requestUuid().equals(evidence.requestUuid()) + || !request.canonicalAccountUuid().equals(evidence.canonicalAccountUuid()) + || !request.expectedTarget().equals(evidence.target())) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + } + + return characterRepository.captureCanonicalGameplayRosterSnapshot(request, evidence); + } + + private static void requirePreseededOnly(CanonicalGameplayRosterTarget target) { + if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { + throw new UnsupportedOperationException("CANONICAL_GAMEPLAY_ROSTER_ENTRY_POLICY_UNSUPPORTED"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java new file mode 100644 index 0000000000..a5be205c33 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** Immutable point-in-time roster snapshot; its identity grants no admission or PLAY authority. */ +public record CanonicalGameplayRosterSnapshot( + UUID canonicalAccountUuid, + UUID snapshotUuid, + String snapshotDigest, + CanonicalGameplayRosterTarget target, + List actors) { + public CanonicalGameplayRosterSnapshot { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(snapshotUuid, "snapshotUuid"); + Objects.requireNonNull(target, "target"); + actors = List.copyOf(Objects.requireNonNull(actors, "actors")); + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("snapshotDigest must be a lowercase SHA-256 digest"); + } + if (actors.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Roster snapshot exceeds its bounded size"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java new file mode 100644 index 0000000000..ebe7025be0 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; + +/** Canonical digest of complete owner-resolved target evidence and its ordered persisted roster. */ +public final class CanonicalGameplayRosterSnapshotDigest { + public static final int MAX_ROSTER_SIZE = 100; + private static final String DOMAIN = "firemud.entity.canonical-gameplay-roster.v3"; + + private CanonicalGameplayRosterSnapshotDigest() {} + + public static String compute( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget target, + List actors) { + if (actors.size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Roster exceeds the maximum supported size"); + } + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + write(output, DOMAIN); + write(output, canonicalAccountUuid.toString()); + write(output, target.tenantUuid().toString()); + write(output, target.realmUuid().toString()); + write(output, target.worldSlug()); + write(output, target.realmSlug()); + write(output, target.gameInstanceUuid().toString()); + write(output, Long.toString(target.catalogRevision())); + write(output, Long.toString(target.pointerVersion())); + write(output, Long.toString(target.activeWorldEpoch())); + write(output, target.canonicalVersionUuid().toString()); + write(output, target.publishedPolicyDigest()); + write(output, target.publishedReleaseBundleRef()); + write(output, target.admissionPointerSnapshotDigest()); + write(output, target.publishedOwnerProofDigest()); + write(output, target.playableStateNamespaceId().toString()); + write(output, target.playableStateScope().name()); + write(output, target.entryPolicy().name()); + write(output, Integer.toString(actors.size())); + for (CanonicalGameplayRosterActor actor : actors) { + write(output, actor.characterUuid().toString()); + write(output, actor.displayName()); + } + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode canonical roster snapshot", exception); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java new file mode 100644 index 0000000000..e8dcea1811 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java @@ -0,0 +1,19 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable identity and digest of one previously returned roster snapshot. */ +public record CanonicalGameplayRosterSnapshotReference(UUID snapshotUuid, String snapshotDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterSnapshotReference { + Objects.requireNonNull(snapshotUuid, "snapshotUuid"); + if (NIL_UUID.equals(snapshotUuid)) { + throw new IllegalArgumentException("snapshotUuid must be non-nil"); + } + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("snapshotDigest must be lowercase SHA-256 hex"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java new file mode 100644 index 0000000000..d4a0961a6b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** Complete caller-echoed target precondition, independently resolved by the trusted owner port. */ +public record CanonicalGameplayRosterTarget( + UUID tenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + UUID gameInstanceUuid, + long catalogRevision, + long pointerVersion, + long activeWorldEpoch, + UUID canonicalVersionUuid, + String publishedPolicyDigest, + String publishedReleaseBundleRef, + String admissionPointerSnapshotDigest, + String publishedOwnerProofDigest, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + CanonicalGameplayRosterEntryPolicy entryPolicy) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SLUG_PATTERN = "[a-z0-9][a-z0-9-]{0,63}"; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public CanonicalGameplayRosterTarget { + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + requirePositive(catalogRevision, "catalogRevision"); + requirePositive(pointerVersion, "pointerVersion"); + requirePositive(activeWorldEpoch, "activeWorldEpoch"); + requireNonNil(canonicalVersionUuid, "canonicalVersionUuid"); + requireDigest(publishedPolicyDigest, "publishedPolicyDigest"); + requireDigest(admissionPointerSnapshotDigest, "admissionPointerSnapshotDigest"); + requireDigest(publishedOwnerProofDigest, "publishedOwnerProofDigest"); + requireReleaseRef(publishedReleaseBundleRef); + ActorIdentity.requireScope(playableStateScope); + Objects.requireNonNull(entryPolicy, "entryPolicy"); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } + + private static void requirePositive(long value, String fieldName) { + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + } + + private static void requireSlug(String value, String fieldName) { + if (value == null || !value.matches(SLUG_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical selector"); + } + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !value.matches(DIGEST_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireReleaseRef(String value) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > MAX_RELEASE_REF_LENGTH + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("publishedReleaseBundleRef is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java new file mode 100644 index 0000000000..dcfa117813 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.entitymanagement.service; + +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; + +/** Account-owned canonical UUID provenance read used by the protected actor-assignment path. */ +@FunctionalInterface +public interface PreseededActorAccountIdentityPort { + RuntimeAccountIdentityEvidence resolveRuntimeAccountIdentity( + String canonicalAccountUuid, String assignmentUuid); +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java new file mode 100644 index 0000000000..ecc3bc6206 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Caller-echoed complete target used only as an assignment precondition and grant correlation. + * Owner evidence remains the sole source of authority for these values. + */ +public record PreseededActorAssignmentExpectedTarget( + UUID canonicalTenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + String gameInstanceId, + long catalogRevision, + UUID canonicalVersionUuid, + String frozenPolicyDigest, + UUID playableStateNamespaceId, + String publishedReleaseBundleRef, + PlayableStateScope playableStateScope) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SLUG_PATTERN = "[a-z0-9][a-z0-9-]{0,63}"; + private static final int MAX_GAME_INSTANCE_ID_LENGTH = 255; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public PreseededActorAssignmentExpectedTarget { + requireNonNil(canonicalTenantUuid, "canonicalTenantUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + requireBoundedOpaqueId(gameInstanceId, "gameInstanceId", MAX_GAME_INSTANCE_ID_LENGTH); + requirePositive(catalogRevision, "catalogRevision"); + requireNonNil(canonicalVersionUuid, "canonicalVersionUuid"); + if (frozenPolicyDigest == null || !frozenPolicyDigest.matches(DIGEST_PATTERN)) { + throw new IllegalArgumentException("frozenPolicyDigest must be a lowercase SHA-256 digest"); + } + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !publishedReleaseBundleRef.equals(publishedReleaseBundleRef.trim()) + || publishedReleaseBundleRef.length() > MAX_RELEASE_REF_LENGTH + || publishedReleaseBundleRef.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("publishedReleaseBundleRef is incomplete"); + } + ActorIdentity.requireScope(playableStateScope); + } + + /** Compares every caller-echoed target selector with the independent owner-resolved target. */ + public boolean exactlyMatches(PreseededActorAssignmentOwnerEvidence ownerEvidence) { + return ownerEvidence != null + && canonicalTenantUuid.equals(ownerEvidence.canonicalTenantUuid()) + && realmUuid.equals(ownerEvidence.realmUuid()) + && worldSlug.equals(ownerEvidence.worldSlug()) + && realmSlug.equals(ownerEvidence.realmSlug()) + && gameInstanceId.equals(ownerEvidence.gameInstanceId()) + && catalogRevision == ownerEvidence.catalogRevision() + && canonicalVersionUuid.equals(ownerEvidence.canonicalVersionUuid()) + && frozenPolicyDigest.equals(ownerEvidence.frozenPolicyDigest()) + && playableStateNamespaceId.equals(ownerEvidence.playableStateNamespaceId()) + && publishedReleaseBundleRef.equals(ownerEvidence.publishedReleaseBundleRef()) + && playableStateScope == ownerEvidence.playableStateScope(); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } + + private static void requirePositive(long value, String fieldName) { + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + } + + private static void requireSlug(String value, String fieldName) { + if (value == null || !value.matches(SLUG_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical realm selector"); + } + } + + private static void requireBoundedOpaqueId(String value, String fieldName, int maxLength) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > maxLength + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java new file mode 100644 index 0000000000..baba148e4b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Computes the assignment digest from the caller target before any owner reads are performed. */ +final class PreseededActorAssignmentGrantIntentDigest { + private static final String DOMAIN = "firemud.entity.preseeded-actor-assignment.v4"; + + private PreseededActorAssignmentGrantIntentDigest() {} + + static String compute(PreseededActorAssignmentRequest request) { + var target = request.expectedTarget(); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + write(output, DOMAIN); + write(output, request.assignmentUuid().toString()); + write(output, request.canonicalAccountUuid().toString()); + write(output, request.corePayload().actorKind().name()); + write(output, request.corePayload().displayName()); + write(output, target.canonicalTenantUuid().toString()); + write(output, target.realmUuid().toString()); + write(output, target.worldSlug()); + write(output, target.realmSlug()); + write(output, target.gameInstanceId()); + write(output, Long.toString(target.catalogRevision())); + write(output, target.canonicalVersionUuid().toString()); + write(output, target.frozenPolicyDigest()); + write(output, target.playableStateNamespaceId().toString()); + write(output, target.publishedReleaseBundleRef()); + write(output, target.playableStateScope().name()); + write( + output, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY.name()); + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode assignment grant intent", exception); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java new file mode 100644 index 0000000000..1b5752cf03 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Entity-side canonical digest for the immutable assignment intent. */ +final class PreseededActorAssignmentIntentDigest { + private static final String DOMAIN = "firemud.entity.preseeded-actor-assignment.v4"; + + private PreseededActorAssignmentIntentDigest() {} + + static String compute( + PreseededActorAssignmentRequest request, PreseededActorAssignmentOwnerEvidence evidence) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + write(output, DOMAIN); + write(output, request.assignmentUuid().toString()); + write(output, request.canonicalAccountUuid().toString()); + write(output, request.corePayload().actorKind().name()); + write(output, request.corePayload().displayName()); + write(output, evidence.canonicalTenantUuid().toString()); + write(output, evidence.realmUuid().toString()); + write(output, evidence.worldSlug()); + write(output, evidence.realmSlug()); + write(output, evidence.gameInstanceId()); + write(output, Long.toString(evidence.catalogRevision())); + write(output, evidence.canonicalVersionUuid().toString()); + write(output, evidence.frozenPolicyDigest()); + write(output, evidence.playableStateNamespaceId().toString()); + write(output, evidence.publishedReleaseBundleRef()); + write(output, evidence.playableStateScope().name()); + write(output, evidence.entryPolicy().name()); + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode assignment intent", exception); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java new file mode 100644 index 0000000000..12e959d354 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Point-in-time Account eligibility observation and frozen published target returned by the + * owner-read adapter. {@code CURRENT_AT_REVALIDATION} means Account evidence was revalidated at + * observation time; it is not a held authorization or PLAY grant. Numeric Game Design and Game + * Session row identifiers are intentionally not part of this value. + */ +public record PreseededActorAssignmentOwnerEvidence( + UUID assignmentUuid, + UUID canonicalAccountUuid, + Eligibility eligibility, + Instant eligibilityEvaluatedAt, + long membershipAuthorityGeneration, + String eligibilityEvidenceDigest, + UUID canonicalTenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + String gameInstanceId, + long catalogRevision, + UUID canonicalVersionUuid, + String frozenPolicyDigest, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + PublishedEntryPolicy entryPolicy, + AccountPurpose accountPurpose, + AccountCurrentness accountCurrentness, + String accountAuthoritySnapshotDigest, + String publishedOwnerProofDigest, + String publishedReleaseBundleRef) { + public enum Eligibility { + ELIGIBLE, + INELIGIBLE + } + + public enum PublishedEntryPolicy { + PRESEEDED_ONLY + } + + public enum AccountPurpose { + PRESEEDED_ACTOR_STAGING + } + + public enum AccountCurrentness { + OBSERVED, + /** Point-in-time Account revalidation result; not a held authorization or PLAY grant. */ + CURRENT_AT_REVALIDATION, + CHANGED_SINCE_OBSERVATION + } + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SLUG_PATTERN = "[a-z0-9][a-z0-9-]{0,63}"; + private static final int MAX_GAME_INSTANCE_ID_LENGTH = 255; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public PreseededActorAssignmentOwnerEvidence { + requireNonNil(assignmentUuid, "assignmentUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(eligibility, "eligibility"); + Objects.requireNonNull(eligibilityEvaluatedAt, "eligibilityEvaluatedAt"); + requirePositive(membershipAuthorityGeneration, "membershipAuthorityGeneration"); + requireDigest(eligibilityEvidenceDigest, "eligibilityEvidenceDigest"); + requireNonNil(canonicalTenantUuid, "canonicalTenantUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + requireBoundedOpaqueId(gameInstanceId, "gameInstanceId", MAX_GAME_INSTANCE_ID_LENGTH); + requirePositive(catalogRevision, "catalogRevision"); + requireNonNil(canonicalVersionUuid, "canonicalVersionUuid"); + requireDigest(frozenPolicyDigest, "frozenPolicyDigest"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + ActorIdentity.requireScope(playableStateScope); + Objects.requireNonNull(entryPolicy, "entryPolicy"); + Objects.requireNonNull(accountPurpose, "accountPurpose"); + Objects.requireNonNull(accountCurrentness, "accountCurrentness"); + requireDigest(accountAuthoritySnapshotDigest, "accountAuthoritySnapshotDigest"); + requireDigest(publishedOwnerProofDigest, "publishedOwnerProofDigest"); + if (publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !publishedReleaseBundleRef.equals(publishedReleaseBundleRef.trim()) + || publishedReleaseBundleRef.length() > MAX_RELEASE_REF_LENGTH + || publishedReleaseBundleRef.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("publishedReleaseBundleRef is incomplete"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } + + private static void requirePositive(long value, String fieldName) { + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !value.matches(DIGEST_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireSlug(String value, String fieldName) { + if (value == null || !value.matches(SLUG_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical realm selector"); + } + } + + private static void requireBoundedOpaqueId(String value, String fieldName, int maxLength) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > maxLength + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java new file mode 100644 index 0000000000..e808969519 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.entitymanagement.service; + +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; + +/** + * Game Session owner read for one frozen PRESEEDED_ONLY assignment target, bound to the exact + * Account staging snapshot already read by Entity. + * + *

The production adapter must bind the supplied single Account staging snapshot to the Game + * Session owner-validated canonical tenant, realm, active instance, published release, + * PRESEEDED_ONLY policy/catalog revision, and namespace/scope target. It returns evidence + * independent of the caller's expected-target fields; Entity exact-compares both the target and its + * Account eligibility snapshot before persistence. CURRENT_AT_REVALIDATION is a point-in-time + * Account observation, not a held JOIN authorization, PLAY grant, or admission decision; the + * persisted actor and receipt are non-admitting. Account evidence alone does not satisfy this port. + * The production adapter uses a selector-only Game Session owner read and the one Account staging + * snapshot already read by Entity; it performs no second Account lookup. + */ +public interface PreseededActorAssignmentOwnerEvidencePort { + PreseededActorAssignmentOwnerEvidence resolveCurrentEligibleTarget( + PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + AccountActorStagingEligibilityEvidence stagingEligibilityEvidence); + + final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE"); + } + + public OwnerEvidenceUnavailableException(Throwable cause) { + super("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE", cause); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java new file mode 100644 index 0000000000..2c29cc5e1a --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Immutable readback of a committed, non-admitting PRESEEDED actor assignment and its owner + * snapshots. {@code CURRENT_AT_REVALIDATION} records an Account observation made at that point in + * time; it is neither a held Account authorization nor a PLAY grant, and this receipt does not + * authorize runtime admission or activation. + */ +public record PreseededActorAssignmentReceipt( + UUID assignmentUuid, + UUID canonicalAccountUuid, + UUID characterUuid, + String intentDigest, + PreseededActorAssignmentExpectedTarget target, + PreseededActorCorePayload corePayload, + int accountIdentitySchemaVersion, + String accountIdentityTargetNamespace, + long sourceAccountRowId, + String accountUuidProvenance, + PreseededActorAssignmentOwnerEvidence.Eligibility eligibility, + Instant eligibilityEvaluatedAt, + long membershipAuthorityGeneration, + String eligibilityEvidenceDigest, + String accountAuthoritySnapshotDigest, + PreseededActorAssignmentOwnerEvidence.AccountPurpose accountPurpose, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness accountCurrentness, + String publishedOwnerProofDigest, + String publishedReleaseBundleRef, + String entryPolicy, + String status) { + public PreseededActorAssignmentReceipt { + Objects.requireNonNull(assignmentUuid, "assignmentUuid"); + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(characterUuid, "characterUuid"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(corePayload, "corePayload"); + Objects.requireNonNull(eligibility, "eligibility"); + Objects.requireNonNull(eligibilityEvaluatedAt, "eligibilityEvaluatedAt"); + Objects.requireNonNull(accountPurpose, "accountPurpose"); + Objects.requireNonNull(accountCurrentness, "accountCurrentness"); + if (intentDigest == null + || !intentDigest.matches("[0-9a-f]{64}") + || accountIdentitySchemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(accountIdentityTargetNamespace) + || sourceAccountRowId <= 0L + || !isRecognizedAccountUuidProvenance(accountUuidProvenance) + || eligibility != PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE + || membershipAuthorityGeneration <= 0 + || eligibilityEvidenceDigest == null + || !eligibilityEvidenceDigest.matches("[0-9a-f]{64}") + || accountAuthoritySnapshotDigest == null + || !accountAuthoritySnapshotDigest.matches("[0-9a-f]{64}") + || publishedOwnerProofDigest == null + || !publishedOwnerProofDigest.matches("[0-9a-f]{64}") + || publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || publishedReleaseBundleRef.length() > 1024 + || accountPurpose + != PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING + || accountCurrentness + != PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION + || !"PRESEEDED_ONLY".equals(entryPolicy) + || !target.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !"ASSIGNED".equals(status)) { + throw new IllegalArgumentException("Committed PRESEEDED assignment receipt is incomplete"); + } + PreseededActorAssignmentRequest intent = + new PreseededActorAssignmentRequest( + assignmentUuid, canonicalAccountUuid, corePayload, target); + if (!intentDigest.equals(intent.mutationIntentDigest())) { + throw new IllegalArgumentException("Committed PRESEEDED assignment intent digest is invalid"); + } + } + + /** + * Returns the persisted point-in-time result; it does not assert eligibility is still current. + */ + public boolean eligibleAtRevalidation() { + return eligibility == PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE; + } + + private static boolean isRecognizedAccountUuidProvenance(String provenance) { + return "ACCOUNT_V29_MIGRATION".equals(provenance) + || "ACCOUNT_REPOSITORY_INSERT".equals(provenance) + || "ACCOUNT_DATABASE_INSERT".equals(provenance); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java new file mode 100644 index 0000000000..01f40fab75 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable operation/actor selector for Entity's assignment receipt owner read. */ +public record PreseededActorAssignmentReceiptRequest( + UUID assignmentUuid, + UUID canonicalAccountUuid, + UUID characterUuid, + String intentDigest, + PreseededActorAssignmentExpectedTarget expectedTarget) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PreseededActorAssignmentReceiptRequest { + requireNonNil(assignmentUuid, "assignmentUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(characterUuid, "characterUuid"); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("intentDigest must be lowercase SHA-256 hex"); + } + Objects.requireNonNull(expectedTarget, "expectedTarget"); + } + + 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"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java new file mode 100644 index 0000000000..5416948a51 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; + +/** Exposes only repository-verified committed receipts for owner-resolved assigned actors. */ +public final class PreseededActorAssignmentReceiptService { + private final CharacterRepository characterRepository; + + public PreseededActorAssignmentReceiptService(CharacterRepository characterRepository) { + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public Optional read( + PreseededActorAssignmentReceiptRequest request) { + Objects.requireNonNull(request, "request"); + return characterRepository.readPreseededActorAssignmentReceipt(request); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java new file mode 100644 index 0000000000..547ddff9d1 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Stable operation identity and the exact minimal core payload requested for assignment. */ +public record PreseededActorAssignmentRequest( + UUID assignmentUuid, + UUID canonicalAccountUuid, + PreseededActorCorePayload corePayload, + PreseededActorAssignmentExpectedTarget expectedTarget) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PreseededActorAssignmentRequest { + requireNonNil(assignmentUuid, "assignmentUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(corePayload, "corePayload"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + } + + /** + * Stable operation digest computed from caller intent, never from transient owner observations. + */ + public String mutationIntentDigest() { + return PreseededActorAssignmentGrantIntentDigest.compute(this); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java new file mode 100644 index 0000000000..9da512e869 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** + * Persisted outcome for a digest-bound pre-seeded assignment attempt. {@code ASSIGNED} means only + * that Entity persisted the actor; it is not a PLAY grant or runtime-admission result. + */ +public record PreseededActorAssignmentResult( + UUID assignmentUuid, Outcome outcome, UUID characterUuid, String intentDigest) { + public enum Outcome { + ASSIGNED, + IDEMPOTENCY_CONFLICT + } + + public PreseededActorAssignmentResult { + Objects.requireNonNull(assignmentUuid, "assignmentUuid"); + Objects.requireNonNull(outcome, "outcome"); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("intentDigest must be a lowercase SHA-256 digest"); + } + if ((outcome == Outcome.ASSIGNED) != (characterUuid != null)) { + throw new IllegalArgumentException("Only assigned outcomes carry a character UUID"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java new file mode 100644 index 0000000000..fcf99a1624 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; + +/** + * Entity-owned persistence boundary behind a dedicated run-owned bootstrap action. Successful + * assignment persists a non-admitting PRESEEDED actor and receipt; it does not grant PLAY or + * authorize runtime activation. + */ +public final class PreseededActorAssignmentService { + private final RunOwnedPreseededAssignmentAuthority runAuthority; + private final PreseededActorAccountIdentityPort accountIdentityPort; + private final PreseededActorStagingEligibilityPort stagingEligibilityPort; + private final PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort; + private final CharacterRepository characterRepository; + + public PreseededActorAssignmentService( + RunOwnedPreseededAssignmentAuthority runAuthority, + PreseededActorAccountIdentityPort accountIdentityPort, + PreseededActorStagingEligibilityPort stagingEligibilityPort, + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + this.runAuthority = Objects.requireNonNull(runAuthority, "runAuthority"); + this.accountIdentityPort = Objects.requireNonNull(accountIdentityPort, "accountIdentityPort"); + this.stagingEligibilityPort = + Objects.requireNonNull(stagingEligibilityPort, "stagingEligibilityPort"); + this.ownerEvidencePort = Objects.requireNonNull(ownerEvidencePort, "ownerEvidencePort"); + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public PreseededActorAssignmentResult assign(PreseededActorAssignmentRequest request) { + Objects.requireNonNull(request, "request"); + runAuthority.requireAuthorized( + request, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + + RuntimeAccountIdentityEvidence accountIdentity = + accountIdentityPort.resolveRuntimeAccountIdentity( + request.canonicalAccountUuid().toString(), request.assignmentUuid().toString()); + requireExactAccountProof(request, accountIdentity); + + // One current Account staging snapshot is a non-admitting predicate, not held JOIN authority. + AccountActorStagingEligibilityEvidence stagingEligibility = + stagingEligibilityPort.resolvePreseededActorStagingEligibility( + request.canonicalAccountUuid().toString(), + request.expectedTarget().canonicalTenantUuid().toString(), + request.assignmentUuid().toString()); + requireExactStagingProof(request, accountIdentity, stagingEligibility); + + PreseededActorAssignmentOwnerEvidence target = + ownerEvidencePort.resolveCurrentEligibleTarget( + request, accountIdentity, stagingEligibility); + requireExactEligibleTarget(request, target, stagingEligibility); + + String intentDigest = PreseededActorAssignmentIntentDigest.compute(request, target); + if (!request.mutationIntentDigest().equals(intentDigest)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_MUTATION_INTENT_DIGEST_MISMATCH"); + } + // Re-read the run-owned capability against the independently resolved target immediately + // before entering the atomic owner repository operation. + runAuthority.requireTargetBoundAuthorized( + request, target, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + return characterRepository.assignPreseededActor(request, target, accountIdentity, intentDigest); + } + + private static void requireExactAccountProof( + PreseededActorAssignmentRequest request, RuntimeAccountIdentityEvidence proof) { + if (proof == null + || !request.assignmentUuid().equals(proof.requestId()) + || !request.canonicalAccountUuid().equals(proof.canonicalAccountId())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_PROOF_MISMATCH"); + } + } + + private static void requireExactStagingProof( + PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence identity, + AccountActorStagingEligibilityEvidence staging) { + if (staging == null + || !request.assignmentUuid().equals(staging.requestId()) + || !request.canonicalAccountUuid().equals(staging.canonicalAccountId()) + || !request.expectedTarget().canonicalTenantUuid().equals(staging.canonicalTenantId()) + || !identity.targetNamespace().equals(staging.targetNamespace()) + || !identity.accountUuidProvenance().equals(staging.accountUuidProvenance())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_MISMATCH"); + } + if (staging.purpose() + != AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY + || staging.currentness() + != AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_REVALIDATION_REQUIRED"); + } + if (staging.decision() != AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + } + } + + private void requireExactEligibleTarget( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence target, + AccountActorStagingEligibilityEvidence staging) { + if (target == null + || !request.assignmentUuid().equals(target.assignmentUuid()) + || !request.canonicalAccountUuid().equals(target.canonicalAccountUuid())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OWNER_PROOF_MISMATCH"); + } + if (target.eligibility() != PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + } + if (target.accountPurpose() + != PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING + || target.accountCurrentness() + != PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_REVALIDATION_REQUIRED"); + } + if (target.entryPolicy() + != PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_POLICY_MISMATCH"); + } + if (!request.expectedTarget().exactlyMatches(target)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + if (!target.canonicalTenantUuid().equals(staging.canonicalTenantId()) + || target.eligibilityEvaluatedAt() == null + || !target.eligibilityEvaluatedAt().equals(staging.observedAt()) + || target.membershipAuthorityGeneration() != staging.membershipAuthorityGeneration() + || !target.eligibilityEvidenceDigest().equals(staging.eligibilityDecisionDigest()) + || !target.accountAuthoritySnapshotDigest().equals(staging.authoritySnapshotDigest())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_MISMATCH"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java new file mode 100644 index 0000000000..7d9d10bec5 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; + +/** Minimal Entity-owned core for a newly assigned player actor; it carries no authored state. */ +public record PreseededActorCorePayload(ActorKind actorKind, String displayName) { + public enum ActorKind { + PLAYER + } + + private static final int MAX_DISPLAY_NAME_CODE_POINTS = 100; + + public PreseededActorCorePayload { + Objects.requireNonNull(actorKind, "actorKind"); + if (actorKind != ActorKind.PLAYER) { + throw new IllegalArgumentException("Only the canonical PLAYER actor kind can be assigned"); + } + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.codePointCount(0, displayName.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || hasUnpairedSurrogate(displayName) + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("displayName must be bounded printable text"); + } + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java new file mode 100644 index 0000000000..918d919b19 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.entitymanagement.service; + +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; + +/** + * Account-owned, point-in-time staging predicate read; this is not gameplay admission authority. + */ +@FunctionalInterface +public interface PreseededActorStagingEligibilityPort { + AccountActorStagingEligibilityEvidence resolvePreseededActorStagingEligibility( + String canonicalAccountUuid, String canonicalTenantUuid, String assignmentUuid); +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java new file mode 100644 index 0000000000..853156f038 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.boot.ssl.SslBundles; + +/** Reads the separately provisioned run-owned action grant at both protected service boundaries. */ +public final class RunOwnedPreseededActorAssignmentAuthorityAdapter + implements RunOwnedPreseededAssignmentAuthority { + private final String capabilityPath; + private final String runId; + private final String composeProjectName; + private final String trustedGameSessionNamespace; + private final Supplier entityServerTrustRootFingerprint; + + RunOwnedPreseededActorAssignmentAuthorityAdapter( + String capabilityPath, + String runId, + String composeProjectName, + String trustedGameSessionNamespace, + Supplier entityServerTrustRootFingerprint) { + this.capabilityPath = capabilityPath; + this.runId = runId; + this.composeProjectName = composeProjectName; + this.trustedGameSessionNamespace = trustedGameSessionNamespace; + this.entityServerTrustRootFingerprint = entityServerTrustRootFingerprint; + } + + public static RunOwnedPreseededActorAssignmentAuthorityAdapter forActiveServerTrustBundle( + String capabilityPath, + String runId, + String composeProjectName, + String trustedGameSessionNamespace, + SslBundles sslBundles, + String activeServerBundleName, + String entityServerTrustRootPath) { + return new RunOwnedPreseededActorAssignmentAuthorityAdapter( + capabilityPath, + runId, + composeProjectName, + trustedGameSessionNamespace, + () -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + sslBundles, activeServerBundleName, entityServerTrustRootPath)); + } + + @Override + public void requireAuthorized(PreseededActorAssignmentRequest request, Action dedicatedAction) { + requireExactPeer(); + requireAction(dedicatedAction); + RunOwnedPreseededActorAssignmentCapability capability = readCapability(); + if (!capability.matchesRequest(request)) { + throw denied(); + } + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence exactTarget, + Action dedicatedAction) { + requireExactPeer(); + requireAction(dedicatedAction); + RunOwnedPreseededActorAssignmentCapability capability = readCapability(); + if (!capability.matchesOwnerTarget(request, exactTarget)) { + throw denied(); + } + } + + private RunOwnedPreseededActorAssignmentCapability readCapability() { + try { + return RunOwnedPreseededActorAssignmentCapability.load( + capabilityPath, + runId, + composeProjectName, + trustedGameSessionNamespace, + entityServerTrustRootFingerprint.get()); + } catch (RuntimeException exception) { + throw denied(); + } + } + + private void requireExactPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (SessionContext.hasAuthenticatedCallerContext() + || peer == null + || !GrpcPeerIdentity.isValidNamespace(trustedGameSessionNamespace) + || !peer.isInNamespace(trustedGameSessionNamespace) + || !peer.isService("game-session-service") + || !peer.uri() + .equals( + "spiffe://firemud/ns/" + + trustedGameSessionNamespace + + "/sa/game-session-service")) { + throw denied(); + } + } + + private static void requireAction(Action action) { + if (action != Action.PRESEEDED_ACTOR_ASSIGNMENT) { + throw denied(); + } + } + + private static AdminAuthorizationException denied() { + return new AdminAuthorizationException( + "PRESEEDED_ASSIGNMENT_RUN_OWNED_ACTION_GRANT_UNAVAILABLE_OR_MISMATCHED"); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java new file mode 100644 index 0000000000..ae90c2ebcd --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java @@ -0,0 +1,602 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.core.io.ClassPathResource; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Read-only, exact run-owned grant for one immutable PRESEEDED actor-assignment intent. */ +public final class RunOwnedPreseededActorAssignmentCapability { + static final String CAPABILITY_SCHEMA = "firemud.run-owned-preseeded-actor-assignment.v3"; + static final String ACTION = "PRESEEDED_ACTOR_ASSIGNMENT"; + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final String URI_PREFIX = "spiffe://firemud/ns/"; + private static final String URI_SUFFIX = "/sa/game-session-service"; + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SAFE_ID_PATTERN = "[a-z0-9][a-z0-9-]{0,127}"; + private static final int MAX_CAPABILITY_BYTES = 16 * 1024; + private static final int MAX_TRUST_ROOT_BYTES = 1024 * 1024; + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "action", + "trustedGameSessionUriSan", + "trustedGameSessionNamespace", + "assignmentUuid", + "canonicalAccountUuid", + "expectedTarget", + "corePayload", + "intentDigest", + "entityServerTrustRootSha256"); + private static final Set TARGET_FIELDS = + Set.of( + "canonicalTenantUuid", + "realmUuid", + "worldSlug", + "realmSlug", + "gameInstanceId", + "catalogRevision", + "canonicalVersionUuid", + "frozenPolicyDigest", + "playableStateNamespaceUuid", + "publishedReleaseBundleRef", + "playableStateScope"); + private static final Set CORE_FIELDS = Set.of("actorKind", "displayName"); + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + + private final String runId; + private final String composeProjectName; + private final String trustedGameSessionUriSan; + private final String trustedGameSessionNamespace; + private final PreseededActorAssignmentRequest request; + private final String intentDigest; + private final String entityServerTrustRootSha256; + + private RunOwnedPreseededActorAssignmentCapability( + String runId, + String composeProjectName, + String trustedGameSessionUriSan, + String trustedGameSessionNamespace, + PreseededActorAssignmentRequest request, + String intentDigest, + String entityServerTrustRootSha256) { + this.runId = runId; + this.composeProjectName = composeProjectName; + this.trustedGameSessionUriSan = trustedGameSessionUriSan; + this.trustedGameSessionNamespace = trustedGameSessionNamespace; + this.request = request; + this.intentDigest = intentDigest; + this.entityServerTrustRootSha256 = entityServerTrustRootSha256; + } + + static RunOwnedPreseededActorAssignmentCapability load( + String capabilityPath, + String expectedRunId, + String expectedComposeProjectName, + String expectedGameSessionNamespace, + String expectedEntityServerTrustRootSha256) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + requireGameSessionNamespace(expectedGameSessionNamespace); + if (capabilityPath == null || capabilityPath.isBlank()) { + throw invalidCapability(); + } + String expectedGameSessionUri = URI_PREFIX + expectedGameSessionNamespace + URI_SUFFIX; + byte[] capabilityBytes; + try { + capabilityBytes = readCapability(Path.of(capabilityPath)); + } catch (RuntimeException exception) { + throw invalidCapability(); + } + return parseAndValidate( + capabilityBytes, + expectedRunId, + expectedComposeProjectName, + expectedGameSessionUri, + expectedGameSessionNamespace, + expectedEntityServerTrustRootSha256); + } + + static RunOwnedPreseededActorAssignmentCapability parseAndValidate( + byte[] capabilityBytes, + String expectedRunId, + String expectedComposeProjectName, + String expectedGameSessionUri, + String expectedGameSessionNamespace, + String expectedEntityServerTrustRootSha256) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + requireGameSessionNamespace(expectedGameSessionNamespace); + if (capabilityBytes == null + || capabilityBytes.length == 0 + || capabilityBytes.length > MAX_CAPABILITY_BYTES + || !isExpectedGameSessionUri(expectedGameSessionUri, expectedGameSessionNamespace) + || expectedEntityServerTrustRootSha256 == null + || !expectedEntityServerTrustRootSha256.matches(DIGEST_PATTERN)) { + throw invalidCapability(); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(decodeUtf8(capabilityBytes)); + } catch (CharacterCodingException | JacksonException exception) { + throw invalidCapability(); + } + if (root == null || !root.isObject() || !hasExactFields(root, ROOT_FIELDS)) { + throw invalidCapability(); + } + + String schema = requiredText(root, "schema"); + String runId = requiredText(root, "runId"); + String composeProjectName = requiredText(root, "composeProjectName"); + String action = requiredText(root, "action"); + String trustedUri = requiredText(root, "trustedGameSessionUriSan"); + String trustedNamespace = requiredText(root, "trustedGameSessionNamespace"); + UUID assignmentUuid = requiredCanonicalUuid(root, "assignmentUuid"); + UUID accountUuid = requiredCanonicalUuid(root, "canonicalAccountUuid"); + PreseededActorAssignmentExpectedTarget target = parseTarget(root.get("expectedTarget")); + PreseededActorCorePayload corePayload = parseCorePayload(root.get("corePayload")); + String intentDigest = requiredText(root, "intentDigest"); + String entityTrustRoot = requiredText(root, "entityServerTrustRootSha256"); + + if (!CAPABILITY_SCHEMA.equals(schema) + || !runId.equals(expectedRunId) + || !composeProjectName.equals(expectedComposeProjectName) + || !ACTION.equals(action) + || !trustedUri.equals(expectedGameSessionUri) + || !trustedNamespace.equals(expectedGameSessionNamespace) + || !entityTrustRoot.equals(expectedEntityServerTrustRootSha256) + || !intentDigest.matches(DIGEST_PATTERN)) { + throw invalidCapability(); + } + + PreseededActorAssignmentRequest request = + new PreseededActorAssignmentRequest(assignmentUuid, accountUuid, corePayload, target); + if (!intentDigest.equals(PreseededActorAssignmentGrantIntentDigest.compute(request))) { + throw invalidCapability(); + } + return new RunOwnedPreseededActorAssignmentCapability( + runId, + composeProjectName, + trustedUri, + trustedNamespace, + request, + intentDigest, + entityTrustRoot); + } + + private static PreseededActorAssignmentExpectedTarget parseTarget(JsonNode value) { + if (value == null || !value.isObject() || !hasExactFields(value, TARGET_FIELDS)) { + throw invalidCapability(); + } + PlayableStateScope scope; + try { + scope = PlayableStateScope.valueOf(requiredText(value, "playableStateScope")); + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + try { + return new PreseededActorAssignmentExpectedTarget( + requiredCanonicalUuid(value, "canonicalTenantUuid"), + requiredCanonicalUuid(value, "realmUuid"), + requiredText(value, "worldSlug"), + requiredText(value, "realmSlug"), + requiredText(value, "gameInstanceId"), + requiredPositiveLong(value, "catalogRevision"), + requiredCanonicalUuid(value, "canonicalVersionUuid"), + requiredText(value, "frozenPolicyDigest"), + requiredCanonicalUuid(value, "playableStateNamespaceUuid"), + requiredText(value, "publishedReleaseBundleRef"), + scope); + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + } + + private static PreseededActorCorePayload parseCorePayload(JsonNode value) { + if (value == null || !value.isObject() || !hasExactFields(value, CORE_FIELDS)) { + throw invalidCapability(); + } + if (!"PLAYER".equals(requiredText(value, "actorKind"))) { + throw invalidCapability(); + } + try { + return new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, requiredText(value, "displayName")); + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + } + + public static String configuredTrustRootFingerprint(String configuredPath) { + if (configuredPath == null || configuredPath.isBlank()) { + throw invalidCapability(); + } + byte[] pemBytes = readConfiguredTrustRoot(configuredPath); + try { + Collection certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(pemBytes)); + return fingerprintValidatedTrustRoot(certificates); + } catch (java.security.cert.CertificateException exception) { + throw invalidCapability(); + } + } + + /** + * Pins the exact CA currently installed in the active Entity gRPC server SSL bundle and rejects + * stale, unsupported, or replaced source configuration before the grant is read. + */ + public static String activeTrustRootFingerprint( + SslBundles sslBundles, String activeServerBundleName, String configuredPath) { + if (sslBundles == null || !"firemud-grpc".equals(activeServerBundleName)) { + throw invalidCapability(); + } + try { + String configuredFingerprint = configuredTrustRootFingerprint(configuredPath); + TrustManager[] trustManagers = + sslBundles.getBundle(activeServerBundleName).getManagers().getTrustManagers(); + String activeFingerprint = activeTrustRootFingerprint(trustManagers, configuredFingerprint); + if (!activeFingerprint.equals(configuredFingerprint)) { + throw invalidCapability(); + } + return activeFingerprint; + } catch (RuntimeException exception) { + throw invalidCapability(); + } + } + + static String activeTrustRootFingerprint( + TrustManager[] trustManagers, String configuredFingerprint) { + if (configuredFingerprint == null || !configuredFingerprint.matches(DIGEST_PATTERN)) { + throw invalidCapability(); + } + if (trustManagers == null + || trustManagers.length != 1 + || !(trustManagers[0] instanceof X509TrustManager trustManager)) { + throw invalidCapability(); + } + X509Certificate[] acceptedIssuers = trustManager.getAcceptedIssuers(); + if (acceptedIssuers == null || acceptedIssuers.length != 1) { + throw invalidCapability(); + } + String activeFingerprint = fingerprintValidatedTrustRoot(Arrays.asList(acceptedIssuers)); + if (!activeFingerprint.equals(configuredFingerprint)) { + throw invalidCapability(); + } + return activeFingerprint; + } + + static String fingerprintValidatedTrustRoot(Collection certificates) { + try { + List roots = + certificates.stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .toList(); + if (certificates.size() != 1 || roots.size() != 1) { + throw invalidCapability(); + } + X509Certificate root = roots.getFirst(); + root.checkValidity(); + if (root.getBasicConstraints() < 0) { + throw invalidCapability(); + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(root.getEncoded())); + } catch (java.security.cert.CertificateException | NoSuchAlgorithmException exception) { + throw invalidCapability(); + } + } + + private static byte[] readConfiguredTrustRoot(String configuredPath) { + try { + if (configuredPath.startsWith("classpath:")) { + ClassPathResource resource = + new ClassPathResource(configuredPath.substring("classpath:".length())); + try (InputStream input = resource.getInputStream()) { + byte[] bytes = input.readNBytes(MAX_TRUST_ROOT_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_TRUST_ROOT_BYTES) { + throw invalidCapability(); + } + return bytes; + } + } + Path configuredFile = + configuredPath.startsWith("file:") + ? Path.of(java.net.URI.create(configuredPath)) + : Path.of(configuredPath); + if (!configuredFile.isAbsolute()) { + configuredFile = configuredFile.toAbsolutePath().normalize(); + } + return readBoundedRegularFile(configuredFile, MAX_TRUST_ROOT_BYTES, false); + } catch (IOException | RuntimeException exception) { + throw invalidCapability(); + } + } + + static byte[] readCapability(Path path) { + return readBoundedRegularFile(path, MAX_CAPABILITY_BYTES, true); + } + + private static byte[] readBoundedRegularFile(Path path, int maxBytes, boolean strictCapability) { + if (path == null || !path.isAbsolute()) { + throw invalidCapability(); + } + Path normalized = path.normalize(); + Path parent = normalized.getParent(); + if (!normalized.equals(path) || parent == null) { + throw invalidCapability(); + } + try { + requireNoSymlinkComponents(normalized); + BasicFileAttributes parentBefore = + Files.readAttributes(parent, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + BasicFileAttributes before = + Files.readAttributes(normalized, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + long processUid = processUid(); + long ownerUid = unixUid(normalized); + if (!parentBefore.isDirectory() + || Files.isSymbolicLink(parent) + || !before.isRegularFile() + || Files.isSymbolicLink(normalized) + || before.fileKey() == null + || before.size() <= 0L + || before.size() > maxBytes + || (strictCapability && ownerUid != processUid) + || !safeReadPermissions(normalized, strictCapability) + || (strictCapability && !safeCapabilityDirectory(parent, processUid))) { + throw invalidCapability(); + } + + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) before.size()); + try (SeekableByteChannel channel = + Files.newByteChannel( + normalized, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)); + InputStream input = Channels.newInputStream(channel)) { + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + if (read == 0) { + continue; + } + if (bytes.size() + read > maxBytes) { + throw invalidCapability(); + } + bytes.write(buffer, 0, read); + } + } + + BasicFileAttributes after = + Files.readAttributes(normalized, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + BasicFileAttributes parentAfter = + Files.readAttributes(parent, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || Files.isSymbolicLink(normalized) + || after.fileKey() == null + || !before.fileKey().equals(after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !sameFileKey(parentBefore.fileKey(), parentAfter.fileKey()) + || ownerUid != unixUid(normalized) + || !safeReadPermissions(normalized, strictCapability) + || (strictCapability && !safeCapabilityDirectory(parent, processUid))) { + throw invalidCapability(); + } + return bytes.toByteArray(); + } catch (IOException | SecurityException exception) { + throw invalidCapability(); + } + } + + private static void requireNoSymlinkComponents(Path path) throws IOException { + for (Path component = path; component != null; component = component.getParent()) { + if (Files.isSymbolicLink(component)) { + throw invalidCapability(); + } + BasicFileAttributes attributes = + Files.readAttributes(component, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (component.equals(path) ? !attributes.isRegularFile() : !attributes.isDirectory()) { + throw invalidCapability(); + } + } + } + + private static boolean safeReadPermissions(Path path, boolean strictCapability) + throws IOException { + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + if (strictCapability) { + return permissions.equals( + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + } + return permissions.contains(PosixFilePermission.OWNER_READ) + && !permissions.contains(PosixFilePermission.OWNER_WRITE) + && !permissions.contains(PosixFilePermission.GROUP_WRITE) + && !permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean safeCapabilityDirectory(Path path, long processUid) throws IOException { + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Set privateDirectoryPermissions = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.OWNER_WRITE); + Set readOnlyPrivateDirectoryPermissions = + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_EXECUTE); + return unixUid(path) == processUid + && (permissions.equals(privateDirectoryPermissions) + || permissions.equals(readOnlyPrivateDirectoryPermissions)); + } + + private static long unixUid(Path path) throws IOException { + Object uid = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(uid instanceof Number number)) { + throw new IOException("Owner identity is unavailable"); + } + return number.longValue(); + } + + private static long processUid() throws IOException { + Path processDirectory = Path.of("/proc", Long.toString(ProcessHandle.current().pid())); + return unixUid(processDirectory); + } + + private static boolean sameFileKey(Object before, Object after) { + return before != null && before.equals(after); + } + + private static boolean hasExactFields(JsonNode node, Set expectedFields) { + Set actualFields = new HashSet<>(); + node.properties().forEach(property -> actualFields.add(property.getKey())); + return actualFields.equals(expectedFields); + } + + private static long requiredPositiveLong(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw invalidCapability(); + } + long parsed = value.longValue(); + if (parsed <= 0L) { + throw invalidCapability(); + } + return parsed; + } + + private static UUID requiredCanonicalUuid(JsonNode root, String field) { + String value = requiredText(root, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L)) { + throw invalidCapability(); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + } + + private static String requiredText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidCapability(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > 256 + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidCapability(); + } + return parsed; + } + + private static String decodeUtf8(byte[] bytes) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } + + private static void requireExpectedRunBinding(String runId, String composeProjectName) { + if (!isSafeId(runId) || !isSafeId(composeProjectName)) { + throw invalidCapability(); + } + } + + private static void requireGameSessionNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw invalidCapability(); + } + } + + private static boolean isSafeId(String value) { + return value != null && value.matches(SAFE_ID_PATTERN); + } + + private static boolean isExpectedGameSessionUri(String uri, String namespace) { + return uri != null + && uri.equals(URI_PREFIX + namespace + URI_SUFFIX) + && GrpcPeerIdentity.parseUri(uri) + .filter(identity -> identity.isInNamespace(namespace)) + .filter(identity -> identity.isService(GAME_SESSION_SERVICE)) + .isPresent(); + } + + boolean matchesRequest(PreseededActorAssignmentRequest candidate) { + return candidate != null + && request.assignmentUuid().equals(candidate.assignmentUuid()) + && request.canonicalAccountUuid().equals(candidate.canonicalAccountUuid()) + && request.corePayload().equals(candidate.corePayload()) + && request.expectedTarget().equals(candidate.expectedTarget()) + && intentDigest.equals(PreseededActorAssignmentGrantIntentDigest.compute(candidate)); + } + + boolean matchesOwnerTarget( + PreseededActorAssignmentRequest candidate, + PreseededActorAssignmentOwnerEvidence ownerEvidence) { + return matchesRequest(candidate) + && ownerEvidence != null + && candidate.assignmentUuid().equals(ownerEvidence.assignmentUuid()) + && candidate.canonicalAccountUuid().equals(ownerEvidence.canonicalAccountUuid()) + && candidate.expectedTarget().exactlyMatches(ownerEvidence) + && intentDigest.equals( + PreseededActorAssignmentIntentDigest.compute(candidate, ownerEvidence)); + } + + private static InvalidCapabilityException invalidCapability() { + return new InvalidCapabilityException(); + } + + /** Generic content-free denial marker; callers must not log capability contents. */ + static final class InvalidCapabilityException extends IllegalArgumentException { + private InvalidCapabilityException() { + super("Run-owned PRESEEDED assignment capability is invalid"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java new file mode 100644 index 0000000000..b600bd605e --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** + * Verifies the exact dedicated run-owned assignment action and target-bound grant. + * + *

The production adapter validates the TLS-authenticated caller and a separately provisioned + * run-owned read-only capability, then binds the dedicated action to the stable assignment UUID, + * Account UUID, caller-echoed expected target, owner-resolved target, and complete core payload. + * The expected target is a correlation/precondition only; it does not authorize its own values. + * Run/project labels, fixture operation IDs, initial-bind authority, and numeric defaults are not + * grants. The adapter remains explicitly disabled by default. + */ +public interface RunOwnedPreseededAssignmentAuthority { + enum Action { + PRESEEDED_ACTOR_ASSIGNMENT + } + + /** + * Authenticates the caller and dedicated action before any owner reads or replay lookup. A + * same-assignment grant mismatch must fail as an intent conflict without disclosing stored data. + * The grant must bind the full request, including its expected target and payload. + */ + void requireAuthorized(PreseededActorAssignmentRequest request, Action dedicatedAction); + + /** + * Rechecks the same authenticated grant against the current complete owner target and payload. A + * mismatch with either the owner target or caller-echoed expected target must fail as an intent + * conflict without returning an actor identity or stored outcome. + */ + void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence exactTarget, + Action dedicatedAction); +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java deleted file mode 100644 index f332900029..0000000000 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeInstanceCleanupHeldException.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.firedevops.firemud.entitymanagement.service; - -public final class RuntimeInstanceCleanupHeldException extends IllegalStateException { - public RuntimeInstanceCleanupHeldException(String message) { - super(message); - } -} 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/EntityManagementGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java index 836969a212..1e7e410c59 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java @@ -35,7 +35,6 @@ import net.firedevops.firemud.entitymanagement.service.InventoryService; import net.firedevops.firemud.entitymanagement.service.PingService; import net.firedevops.firemud.entitymanagement.service.RoomEntityService; -import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import net.firedevops.firemud.entitymanagement.v1.ActorConditionState; import net.firedevops.firemud.entitymanagement.v1.ActorResourceValue; @@ -1828,14 +1827,6 @@ public void cleanupRuntimeInstance( .setDeletedItemStacks(result.deletedItemStacks()) .setDeletedItemInstances(result.deletedItemInstances()) .setDeletedContainerInstances(result.deletedContainerInstances()); - } catch (RuntimeInstanceCleanupHeldException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CleanupRuntimeInstance", - "FAILED_PRECONDITION", - ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( 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 a241b35a63..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,19 +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.service.RuntimeInstanceCleanupHeldException; +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 @@ -29,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 RuntimeInstanceCleanupHeldException( - "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/db/migration/V1006__preseeded_actor_assignment.sql b/services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql new file mode 100644 index 0000000000..99008404ac --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql @@ -0,0 +1,208 @@ +CREATE TABLE entity_tenant_identities ( + entity_tenant_row_id BIGSERIAL PRIMARY KEY, + canonical_tenant_uuid UUID NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_entity_tenant_identity_non_nil + CHECK (canonical_tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) +); + +-- Legacy owner-resolved fixture/data rows are not trusted when one account has multiple actors +-- in one durable namespace. Quarantine every member of an ambiguous group; never pick a winner. +/* [jooq ignore start] */ +WITH ambiguous_account_namespaces AS ( + SELECT tenant_uuid, account_uuid, playable_state_namespace_id + FROM characters + WHERE actor_identity_status = 'OWNER_RESOLVED' + GROUP BY tenant_uuid, account_uuid, playable_state_namespace_id + HAVING COUNT(*) > 1 +) +UPDATE characters AS actor +SET actor_identity_status = 'QUARANTINED', + actor_identity_quarantine_reason = 'AMBIGUOUS_ACCOUNT_NAMESPACE' +FROM ambiguous_account_namespaces AS ambiguous +WHERE actor.actor_identity_status = 'OWNER_RESOLVED' + AND actor.tenant_uuid = ambiguous.tenant_uuid + AND actor.account_uuid = ambiguous.account_uuid + AND actor.playable_state_namespace_id = ambiguous.playable_state_namespace_id; + +CREATE UNIQUE INDEX ux_characters_owner_resolved_account_namespace + ON characters (tenant_uuid, account_uuid, playable_state_namespace_id) + WHERE actor_identity_status = 'OWNER_RESOLVED'; +/* [jooq ignore stop] */ + +CREATE TABLE entity_preseeded_actor_assignment_operations ( + assignment_uuid UUID PRIMARY KEY, + intent_digest VARCHAR(64) NOT NULL, + account_uuid UUID NOT NULL, + account_uuid_provenance VARCHAR(32) NOT NULL, + eligibility_evaluated_at TIMESTAMPTZ NOT NULL, + membership_authority_generation BIGINT NOT NULL, + eligibility_evidence_digest VARCHAR(64) NOT NULL, + tenant_uuid UUID NOT NULL, + realm_uuid UUID NOT NULL, + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + game_instance_id VARCHAR(255) NOT NULL, + catalog_revision BIGINT NOT NULL, + published_version_id BIGINT NOT NULL, + published_version_number INTEGER NOT NULL, + frozen_policy_digest VARCHAR(64) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + entry_policy VARCHAR(32) NOT NULL DEFAULT 'PRESEEDED_ONLY', + actor_kind VARCHAR(16) NOT NULL, + display_name VARCHAR(100) NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'PENDING', + character_uuid UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + completed_at TIMESTAMPTZ, + CONSTRAINT ck_entity_preseeded_assignment_uuid_non_nil + CHECK (assignment_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_account_non_nil + CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_realm_non_nil + CHECK (realm_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_namespace_non_nil + CHECK (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_digest + CHECK (intent_digest ~ '^[0-9a-f]{64}$' + AND eligibility_evidence_digest ~ '^[0-9a-f]{64}$' + AND frozen_policy_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT ck_entity_preseeded_assignment_account_provenance + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )), + CONSTRAINT ck_entity_preseeded_assignment_authority_generation + CHECK (membership_authority_generation > 0), + CONSTRAINT ck_entity_preseeded_assignment_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + )), + CONSTRAINT ck_entity_preseeded_assignment_policy + CHECK (entry_policy = 'PRESEEDED_ONLY'), + CONSTRAINT ck_entity_preseeded_assignment_actor_kind + CHECK (actor_kind = 'PLAYER'), + CONSTRAINT ck_entity_preseeded_assignment_status + CHECK (status IN ('PENDING', 'ASSIGNED', 'IDEMPOTENCY_CONFLICT')), + CONSTRAINT ck_entity_preseeded_assignment_result + CHECK ( + (status = 'PENDING' AND character_uuid IS NULL AND completed_at IS NULL) + OR (status = 'ASSIGNED' AND character_uuid IS NOT NULL AND completed_at IS NOT NULL) + OR (status = 'IDEMPOTENCY_CONFLICT' AND character_uuid IS NULL + AND completed_at IS NOT NULL) + ), + CONSTRAINT ck_entity_preseeded_assignment_positive_versions + CHECK (catalog_revision > 0 AND published_version_id > 0 + AND published_version_number > 0), + CONSTRAINT ck_entity_preseeded_assignment_slugs + CHECK (world_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$' + AND realm_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$'), + CONSTRAINT ck_entity_preseeded_assignment_game_instance + CHECK (length(game_instance_id) > 0 AND game_instance_id = btrim(game_instance_id)), + CONSTRAINT ck_entity_preseeded_assignment_display_name + CHECK (length(display_name) > 0 AND display_name = btrim(display_name)), + CONSTRAINT ux_entity_preseeded_assignment_character UNIQUE (character_uuid) +); + +/* [jooq ignore start] */ +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT fk_entity_preseeded_assignment_tenant_identity + FOREIGN KEY (tenant_uuid) + REFERENCES entity_tenant_identities (canonical_tenant_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT fk_entity_preseeded_assignment_namespace + 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 + ) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT fk_entity_preseeded_assignment_character + FOREIGN KEY (character_uuid) + REFERENCES characters (character_uuid) + DEFERRABLE INITIALLY DEFERRED; +/* [jooq ignore stop] */ + +CREATE INDEX idx_entity_preseeded_assignment_account_target + ON entity_preseeded_actor_assignment_operations ( + tenant_uuid, playable_state_namespace_id, account_uuid, created_at + ); + +/* [jooq ignore start] */ +CREATE FUNCTION reject_entity_tenant_identity_change() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Entity canonical tenant mapping is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER trg_entity_tenant_identity_immutable + BEFORE UPDATE OR DELETE ON entity_tenant_identities + FOR EACH ROW + EXECUTE FUNCTION reject_entity_tenant_identity_change(); + +CREATE FUNCTION reject_entity_assignment_history_removal() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Entity assignment evidence cannot be removed' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER trg_entity_tenant_identity_no_truncate + BEFORE TRUNCATE ON entity_tenant_identities + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); + +CREATE FUNCTION protect_entity_preseeded_actor_assignment_operation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.assignment_uuid, NEW.intent_digest, NEW.account_uuid, NEW.account_uuid_provenance, + NEW.eligibility_evaluated_at, NEW.membership_authority_generation, + NEW.eligibility_evidence_digest, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_id, NEW.catalog_revision, + NEW.published_version_id, NEW.published_version_number, NEW.frozen_policy_digest, + NEW.playable_state_namespace_id, NEW.playable_state_scope, NEW.entry_policy, + NEW.actor_kind, NEW.display_name, NEW.created_at) + IS DISTINCT FROM + (OLD.assignment_uuid, OLD.intent_digest, OLD.account_uuid, OLD.account_uuid_provenance, + OLD.eligibility_evaluated_at, OLD.membership_authority_generation, + OLD.eligibility_evidence_digest, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_id, OLD.catalog_revision, + OLD.published_version_id, OLD.published_version_number, OLD.frozen_policy_digest, + OLD.playable_state_namespace_id, OLD.playable_state_scope, OLD.entry_policy, + OLD.actor_kind, OLD.display_name, OLD.created_at) + OR OLD.status <> 'PENDING' + OR NEW.status NOT IN ('ASSIGNED', 'IDEMPOTENCY_CONFLICT') THEN + RAISE EXCEPTION 'pre-seeded actor assignment intent is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_preseeded_actor_assignment_operation_immutable + BEFORE UPDATE ON entity_preseeded_actor_assignment_operations + FOR EACH ROW + EXECUTE FUNCTION protect_entity_preseeded_actor_assignment_operation(); + +CREATE TRIGGER trg_entity_preseeded_assignment_no_removal + BEFORE DELETE OR TRUNCATE ON entity_preseeded_actor_assignment_operations + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql b/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql new file mode 100644 index 0000000000..807b3f9698 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql @@ -0,0 +1,63 @@ +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD COLUMN account_identity_schema_version SMALLINT NOT NULL, + ADD COLUMN account_identity_target_namespace VARCHAR(63) NOT NULL, + ADD COLUMN source_account_row_id BIGINT NOT NULL, + ADD COLUMN eligibility VARCHAR(16) NOT NULL, + ADD COLUMN account_authority_snapshot_digest VARCHAR(64) NOT NULL, + ADD COLUMN account_purpose VARCHAR(40) NOT NULL, + ADD COLUMN account_currentness VARCHAR(40) NOT NULL, + ADD COLUMN published_owner_proof_digest VARCHAR(64) NOT NULL, + ADD COLUMN published_release_bundle_ref VARCHAR(1024) NOT NULL; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT ck_entity_preseeded_assignment_owner_snapshot + CHECK ( + account_identity_schema_version = 1 + AND account_identity_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND source_account_row_id > 0 + AND eligibility = 'ELIGIBLE' + AND account_authority_snapshot_digest ~ '^[0-9a-f]{64}$' + AND account_purpose = 'PRESEEDED_ACTOR_STAGING' + AND account_currentness = 'CURRENT_AT_REVALIDATION' + AND published_owner_proof_digest ~ '^[0-9a-f]{64}$' + AND length(btrim(published_release_bundle_ref)) > 0 + ); + +/* [jooq ignore start] */ +CREATE OR REPLACE FUNCTION protect_entity_preseeded_actor_assignment_operation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.assignment_uuid, NEW.intent_digest, NEW.account_uuid, NEW.account_uuid_provenance, + NEW.account_identity_schema_version, NEW.account_identity_target_namespace, + NEW.source_account_row_id, NEW.eligibility, + NEW.eligibility_evaluated_at, NEW.membership_authority_generation, + NEW.eligibility_evidence_digest, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_id, NEW.catalog_revision, + NEW.published_version_id, NEW.published_version_number, NEW.frozen_policy_digest, + NEW.playable_state_namespace_id, NEW.playable_state_scope, NEW.entry_policy, + NEW.actor_kind, NEW.display_name, NEW.created_at, + NEW.account_authority_snapshot_digest, NEW.account_purpose, NEW.account_currentness, + NEW.published_owner_proof_digest, NEW.published_release_bundle_ref) + IS DISTINCT FROM + (OLD.assignment_uuid, OLD.intent_digest, OLD.account_uuid, OLD.account_uuid_provenance, + OLD.account_identity_schema_version, OLD.account_identity_target_namespace, + OLD.source_account_row_id, OLD.eligibility, + OLD.eligibility_evaluated_at, OLD.membership_authority_generation, + OLD.eligibility_evidence_digest, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_id, OLD.catalog_revision, + OLD.published_version_id, OLD.published_version_number, OLD.frozen_policy_digest, + OLD.playable_state_namespace_id, OLD.playable_state_scope, OLD.entry_policy, + OLD.actor_kind, OLD.display_name, OLD.created_at, + OLD.account_authority_snapshot_digest, OLD.account_purpose, OLD.account_currentness, + OLD.published_owner_proof_digest, OLD.published_release_bundle_ref) + OR OLD.status <> 'PENDING' + OR NEW.status NOT IN ('ASSIGNED', 'IDEMPOTENCY_CONFLICT') THEN + RAISE EXCEPTION 'pre-seeded actor assignment intent is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql b/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql new file mode 100644 index 0000000000..13dcdddbb9 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql @@ -0,0 +1,221 @@ +CREATE TABLE entity_canonical_gameplay_roster_snapshots ( + snapshot_uuid UUID PRIMARY KEY, + snapshot_digest VARCHAR(64) NOT NULL UNIQUE, + canonical_account_uuid UUID NOT NULL, + tenant_uuid UUID NOT NULL, + realm_uuid UUID NOT NULL, + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + game_instance_uuid UUID NOT NULL, + catalog_revision BIGINT NOT NULL, + published_version_id BIGINT NOT NULL, + published_version_number INTEGER NOT NULL, + published_policy_digest VARCHAR(64) NOT NULL, + published_release_bundle_ref VARCHAR(1024) NOT NULL, + admission_pointer_snapshot_digest VARCHAR(64) NOT NULL, + published_owner_proof_digest VARCHAR(64) NOT NULL, + playable_state_namespace_uuid UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + entry_policy VARCHAR(32) NOT NULL, + roster_count SMALLINT NOT NULL, + construction_state VARCHAR(8) NOT NULL DEFAULT 'BUILDING', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_entity_canonical_roster_snapshot_uuid_non_nil + CHECK (snapshot_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_account_non_nil + CHECK (canonical_account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_realm_non_nil + CHECK (realm_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_instance_non_nil + CHECK (game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_namespace_non_nil + CHECK (playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_digests + CHECK (snapshot_digest ~ '^[0-9a-f]{64}$' + AND published_policy_digest ~ '^[0-9a-f]{64}$' + AND admission_pointer_snapshot_digest ~ '^[0-9a-f]{64}$' + AND published_owner_proof_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT ck_entity_canonical_roster_slug + CHECK (world_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$' + AND realm_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$'), + CONSTRAINT ck_entity_canonical_roster_release_ref + CHECK (length(btrim(published_release_bundle_ref)) > 0), + CONSTRAINT ck_entity_canonical_roster_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', 'PLAYABLE_STATE_SCOPE_ISOLATED')), + CONSTRAINT ck_entity_canonical_roster_policy + CHECK (entry_policy = 'PRESEEDED_ONLY'), + CONSTRAINT ck_entity_canonical_roster_versions + CHECK (catalog_revision > 0 AND published_version_id > 0 + AND published_version_number > 0), + CONSTRAINT ck_entity_canonical_roster_count + CHECK (roster_count BETWEEN 0 AND 100), + CONSTRAINT ck_entity_canonical_roster_construction_state + CHECK (construction_state IN ('BUILDING', 'SEALED')) +); + +CREATE TABLE entity_canonical_gameplay_roster_snapshot_actors ( + snapshot_uuid UUID NOT NULL, + ordinal_position SMALLINT NOT NULL, + character_uuid UUID NOT NULL, + display_name VARCHAR(100) NOT NULL, + actor_kind VARCHAR(16) NOT NULL, + CONSTRAINT pk_entity_canonical_roster_snapshot_actors + PRIMARY KEY (snapshot_uuid, ordinal_position), + CONSTRAINT ux_entity_canonical_roster_snapshot_actor + UNIQUE (snapshot_uuid, character_uuid), + CONSTRAINT ck_entity_canonical_roster_actor_ordinal + CHECK (ordinal_position BETWEEN 0 AND 99), + CONSTRAINT ck_entity_canonical_roster_actor_uuid_non_nil + CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_actor_name + CHECK (length(btrim(display_name)) > 0), + CONSTRAINT ck_entity_canonical_roster_actor_kind + CHECK (actor_kind = 'PLAYER') +); + +/* [jooq ignore start] */ +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT fk_entity_canonical_roster_tenant + FOREIGN KEY (tenant_uuid) + REFERENCES entity_tenant_identities (canonical_tenant_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT fk_entity_canonical_roster_namespace_scope + FOREIGN KEY (tenant_uuid, playable_state_namespace_uuid, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes ( + tenant_uuid, playable_state_namespace_id, playable_state_scope + ) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_canonical_gameplay_roster_snapshot_actors + ADD CONSTRAINT fk_entity_canonical_roster_snapshot + FOREIGN KEY (snapshot_uuid) + REFERENCES entity_canonical_gameplay_roster_snapshots (snapshot_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_canonical_gameplay_roster_snapshot_actors + ADD CONSTRAINT fk_entity_canonical_roster_character + FOREIGN KEY (character_uuid) + REFERENCES characters (character_uuid) + DEFERRABLE INITIALLY DEFERRED; + +CREATE FUNCTION protect_entity_canonical_gameplay_roster_snapshot() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + actor_count INTEGER; + minimum_position SMALLINT; + maximum_position SMALLINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshots cannot be removed' + USING ERRCODE = '23514'; + END IF; + + IF OLD.construction_state <> 'BUILDING' + OR NEW.construction_state <> 'SEALED' + OR (NEW.snapshot_uuid, NEW.snapshot_digest, NEW.canonical_account_uuid, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_uuid, + NEW.catalog_revision, NEW.published_version_id, NEW.published_version_number, + NEW.published_policy_digest, NEW.published_release_bundle_ref, + NEW.admission_pointer_snapshot_digest, NEW.published_owner_proof_digest, + NEW.playable_state_namespace_uuid, NEW.playable_state_scope, NEW.entry_policy, + NEW.roster_count, NEW.created_at) + IS DISTINCT FROM + (OLD.snapshot_uuid, OLD.snapshot_digest, OLD.canonical_account_uuid, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_uuid, + OLD.catalog_revision, OLD.published_version_id, OLD.published_version_number, + OLD.published_policy_digest, OLD.published_release_bundle_ref, + OLD.admission_pointer_snapshot_digest, OLD.published_owner_proof_digest, + OLD.playable_state_namespace_uuid, OLD.playable_state_scope, OLD.entry_policy, + OLD.roster_count, OLD.created_at) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*), min(ordinal_position), max(ordinal_position) + INTO actor_count, minimum_position, maximum_position + FROM entity_canonical_gameplay_roster_snapshot_actors + WHERE snapshot_uuid = OLD.snapshot_uuid; + IF actor_count <> OLD.roster_count + OR (actor_count = 0 AND (minimum_position IS NOT NULL OR maximum_position IS NOT NULL)) + OR (actor_count > 0 AND (minimum_position <> 0 OR maximum_position <> actor_count - 1)) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is incomplete' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION protect_entity_canonical_gameplay_roster_snapshot_actor() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + snapshot_row entity_canonical_gameplay_roster_snapshots%ROWTYPE; + actor_row characters%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot actors are immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO snapshot_row + FROM entity_canonical_gameplay_roster_snapshots + WHERE snapshot_uuid = NEW.snapshot_uuid + FOR UPDATE; + IF NOT FOUND OR snapshot_row.construction_state <> 'BUILDING' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is not being constructed' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO actor_row + FROM characters + WHERE character_uuid = NEW.character_uuid + FOR SHARE; + IF NOT FOUND + OR actor_row.actor_identity_status <> 'OWNER_RESOLVED' + OR actor_row.actor_identity_quarantine_reason IS NOT NULL + OR actor_row.account_uuid <> snapshot_row.canonical_account_uuid + OR actor_row.tenant_uuid <> snapshot_row.tenant_uuid + OR actor_row.playable_state_namespace_id <> snapshot_row.playable_state_namespace_uuid + OR actor_row.playable_state_scope <> snapshot_row.playable_state_scope + OR actor_row.name <> NEW.display_name + OR NEW.actor_kind <> 'PLAYER' THEN + RAISE EXCEPTION 'canonical gameplay roster actor provenance mismatch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_canonical_roster_snapshot_guard + BEFORE UPDATE OR DELETE ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW + EXECUTE FUNCTION protect_entity_canonical_gameplay_roster_snapshot(); + +CREATE TRIGGER trg_entity_canonical_roster_snapshot_no_truncate + BEFORE TRUNCATE ON entity_canonical_gameplay_roster_snapshots + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); + +CREATE TRIGGER trg_entity_canonical_roster_actor_guard + BEFORE INSERT OR UPDATE OR DELETE ON entity_canonical_gameplay_roster_snapshot_actors + FOR EACH ROW + EXECUTE FUNCTION protect_entity_canonical_gameplay_roster_snapshot_actor(); + +CREATE TRIGGER trg_entity_canonical_roster_actor_no_truncate + BEFORE TRUNCATE ON entity_canonical_gameplay_roster_snapshot_actors + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); +/* [jooq ignore stop] */ + +CREATE INDEX idx_entity_canonical_roster_account_target + ON entity_canonical_gameplay_roster_snapshots ( + tenant_uuid, canonical_account_uuid, playable_state_namespace_uuid, created_at + ); diff --git a/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql b/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql new file mode 100644 index 0000000000..22234a4584 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql @@ -0,0 +1,162 @@ +-- V5-V7 evidence remains immutable history. Its numeric publication identifiers do not +-- establish a canonical version UUID and must never be upgraded by inference. +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD COLUMN canonical_version_uuid UUID; +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD COLUMN publication_evidence_format VARCHAR(24) NOT NULL DEFAULT 'LEGACY_NUMERIC'; + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN canonical_version_uuid UUID; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN publication_evidence_format VARCHAR(24) NOT NULL DEFAULT 'LEGACY_NUMERIC'; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ALTER COLUMN published_version_id DROP NOT NULL; +ALTER TABLE entity_preseeded_actor_assignment_operations + ALTER COLUMN published_version_number DROP NOT NULL; +ALTER TABLE entity_preseeded_actor_assignment_operations + ALTER COLUMN publication_evidence_format SET DEFAULT 'CANONICAL_UUID'; +ALTER TABLE entity_preseeded_actor_assignment_operations + DROP CONSTRAINT ck_entity_preseeded_assignment_positive_versions; +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT ck_entity_preseeded_assignment_publication_evidence + CHECK ( + catalog_revision > 0 AND ( + (publication_evidence_format = 'LEGACY_NUMERIC' + AND canonical_version_uuid IS NULL + AND published_version_id > 0 AND published_version_number > 0) + OR (publication_evidence_format = 'CANONICAL_UUID' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL) + ) + ); + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN published_version_id DROP NOT NULL; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN published_version_number DROP NOT NULL; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN publication_evidence_format SET DEFAULT 'CANONICAL_UUID'; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + DROP CONSTRAINT ck_entity_canonical_roster_versions; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT ck_entity_canonical_roster_publication_evidence + CHECK ( + catalog_revision > 0 AND ( + (publication_evidence_format = 'LEGACY_NUMERIC' + AND canonical_version_uuid IS NULL + AND published_version_id > 0 AND published_version_number > 0) + OR (publication_evidence_format = 'CANONICAL_UUID' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL) + ) + ); + +/* [jooq ignore start] */ +CREATE FUNCTION require_current_entity_publication_evidence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.publication_evidence_format <> 'CANONICAL_UUID' THEN + RAISE EXCEPTION 'new Entity publication evidence requires canonical UUID format' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_preseeded_assignment_current_publication + BEFORE INSERT ON entity_preseeded_actor_assignment_operations + FOR EACH ROW + EXECUTE FUNCTION require_current_entity_publication_evidence(); + +CREATE TRIGGER trg_entity_canonical_roster_current_publication + BEFORE INSERT ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW + EXECUTE FUNCTION require_current_entity_publication_evidence(); + +CREATE OR REPLACE FUNCTION protect_entity_preseeded_actor_assignment_operation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF (NEW.assignment_uuid, NEW.intent_digest, NEW.account_uuid, NEW.account_uuid_provenance, + NEW.account_identity_schema_version, NEW.account_identity_target_namespace, + NEW.source_account_row_id, NEW.eligibility, + NEW.eligibility_evaluated_at, NEW.membership_authority_generation, + NEW.eligibility_evidence_digest, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_id, NEW.catalog_revision, + NEW.published_version_id, NEW.published_version_number, NEW.canonical_version_uuid, + NEW.publication_evidence_format, NEW.frozen_policy_digest, + NEW.playable_state_namespace_id, NEW.playable_state_scope, NEW.entry_policy, + NEW.actor_kind, NEW.display_name, NEW.created_at, + NEW.account_authority_snapshot_digest, NEW.account_purpose, NEW.account_currentness, + NEW.published_owner_proof_digest, NEW.published_release_bundle_ref) + IS DISTINCT FROM + (OLD.assignment_uuid, OLD.intent_digest, OLD.account_uuid, OLD.account_uuid_provenance, + OLD.account_identity_schema_version, OLD.account_identity_target_namespace, + OLD.source_account_row_id, OLD.eligibility, + OLD.eligibility_evaluated_at, OLD.membership_authority_generation, + OLD.eligibility_evidence_digest, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_id, OLD.catalog_revision, + OLD.published_version_id, OLD.published_version_number, OLD.canonical_version_uuid, + OLD.publication_evidence_format, OLD.frozen_policy_digest, + OLD.playable_state_namespace_id, OLD.playable_state_scope, OLD.entry_policy, + OLD.actor_kind, OLD.display_name, OLD.created_at, + OLD.account_authority_snapshot_digest, OLD.account_purpose, OLD.account_currentness, + OLD.published_owner_proof_digest, OLD.published_release_bundle_ref) + OR OLD.status <> 'PENDING' + OR NEW.status NOT IN ('ASSIGNED', 'IDEMPOTENCY_CONFLICT') THEN + RAISE EXCEPTION 'pre-seeded actor assignment intent is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION protect_entity_canonical_gameplay_roster_snapshot() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + actor_count INTEGER; + minimum_position SMALLINT; + maximum_position SMALLINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshots cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF OLD.construction_state <> 'BUILDING' + OR NEW.construction_state <> 'SEALED' + OR (NEW.snapshot_uuid, NEW.snapshot_digest, NEW.canonical_account_uuid, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_uuid, + NEW.catalog_revision, NEW.published_version_id, NEW.published_version_number, + NEW.canonical_version_uuid, NEW.publication_evidence_format, + NEW.published_policy_digest, NEW.published_release_bundle_ref, + NEW.admission_pointer_snapshot_digest, NEW.published_owner_proof_digest, + NEW.playable_state_namespace_uuid, NEW.playable_state_scope, NEW.entry_policy, + NEW.roster_count, NEW.created_at) + IS DISTINCT FROM + (OLD.snapshot_uuid, OLD.snapshot_digest, OLD.canonical_account_uuid, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_uuid, + OLD.catalog_revision, OLD.published_version_id, OLD.published_version_number, + OLD.canonical_version_uuid, OLD.publication_evidence_format, + OLD.published_policy_digest, OLD.published_release_bundle_ref, + OLD.admission_pointer_snapshot_digest, OLD.published_owner_proof_digest, + OLD.playable_state_namespace_uuid, OLD.playable_state_scope, OLD.entry_policy, + OLD.roster_count, OLD.created_at) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is immutable' + USING ERRCODE = '23514'; + END IF; + SELECT count(*), min(ordinal_position), max(ordinal_position) + INTO actor_count, minimum_position, maximum_position + FROM entity_canonical_gameplay_roster_snapshot_actors + WHERE snapshot_uuid = OLD.snapshot_uuid; + IF actor_count <> OLD.roster_count + OR (actor_count = 0 AND (minimum_position IS NOT NULL OR maximum_position IS NOT NULL)) + OR (actor_count > 0 AND (minimum_position <> 0 OR maximum_position <> actor_count - 1)) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is incomplete' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql b/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql new file mode 100644 index 0000000000..1fa8a05f38 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql @@ -0,0 +1,108 @@ +-- V1-V8 assignment and roster evidence remains immutable history. Older roster rows did not +-- retain these owner counters, so leave them NULL rather than inferring or fabricating values. +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN pointer_version BIGINT; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN active_world_epoch BIGINT; + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN publication_evidence_format SET DEFAULT 'CANONICAL_UUID_V2'; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + DROP CONSTRAINT ck_entity_canonical_roster_publication_evidence; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT ck_entity_canonical_roster_publication_evidence + CHECK ( + catalog_revision > 0 AND ( + (publication_evidence_format = 'LEGACY_NUMERIC' + AND canonical_version_uuid IS NULL + AND published_version_id > 0 AND published_version_number > 0 + AND pointer_version IS NULL AND active_world_epoch IS NULL) + OR (publication_evidence_format = 'CANONICAL_UUID' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL + AND pointer_version IS NULL AND active_world_epoch IS NULL) + OR (publication_evidence_format = 'CANONICAL_UUID_V2' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL + AND pointer_version IS NOT NULL AND pointer_version > 0 + AND active_world_epoch IS NOT NULL AND active_world_epoch > 0) + ) + ); + +/* [jooq ignore start] */ +DROP TRIGGER trg_entity_canonical_roster_current_publication + ON entity_canonical_gameplay_roster_snapshots; + +CREATE FUNCTION require_current_entity_canonical_roster_evidence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.publication_evidence_format <> 'CANONICAL_UUID_V2' + OR NEW.pointer_version IS NULL OR NEW.pointer_version <= 0 + OR NEW.active_world_epoch IS NULL OR NEW.active_world_epoch <= 0 + OR NEW.canonical_version_uuid IS NULL + OR NEW.canonical_version_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.published_version_id IS NOT NULL + OR NEW.published_version_number IS NOT NULL THEN + RAISE EXCEPTION 'new Entity roster evidence requires exact canonical owner counters' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_canonical_roster_current_publication + BEFORE INSERT ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW + EXECUTE FUNCTION require_current_entity_canonical_roster_evidence(); + +CREATE OR REPLACE FUNCTION protect_entity_canonical_gameplay_roster_snapshot() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + actor_count INTEGER; + minimum_position SMALLINT; + maximum_position SMALLINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshots cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF OLD.construction_state <> 'BUILDING' + OR NEW.construction_state <> 'SEALED' + OR (NEW.snapshot_uuid, NEW.snapshot_digest, NEW.canonical_account_uuid, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_uuid, + NEW.catalog_revision, NEW.published_version_id, NEW.published_version_number, + NEW.canonical_version_uuid, NEW.publication_evidence_format, + NEW.pointer_version, NEW.active_world_epoch, + NEW.published_policy_digest, NEW.published_release_bundle_ref, + NEW.admission_pointer_snapshot_digest, NEW.published_owner_proof_digest, + NEW.playable_state_namespace_uuid, NEW.playable_state_scope, NEW.entry_policy, + NEW.roster_count, NEW.created_at) + IS DISTINCT FROM + (OLD.snapshot_uuid, OLD.snapshot_digest, OLD.canonical_account_uuid, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_uuid, + OLD.catalog_revision, OLD.published_version_id, OLD.published_version_number, + OLD.canonical_version_uuid, OLD.publication_evidence_format, + OLD.pointer_version, OLD.active_world_epoch, + OLD.published_policy_digest, OLD.published_release_bundle_ref, + OLD.admission_pointer_snapshot_digest, OLD.published_owner_proof_digest, + OLD.playable_state_namespace_uuid, OLD.playable_state_scope, OLD.entry_policy, + OLD.roster_count, OLD.created_at) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is immutable' + USING ERRCODE = '23514'; + END IF; + SELECT count(*), min(ordinal_position), max(ordinal_position) + INTO actor_count, minimum_position, maximum_position + FROM entity_canonical_gameplay_roster_snapshot_actors + WHERE snapshot_uuid = OLD.snapshot_uuid; + IF actor_count <> OLD.roster_count + OR (actor_count = 0 AND (minimum_position IS NOT NULL OR maximum_position IS NOT NULL)) + OR (actor_count > 0 AND (minimum_position <> 0 OR maximum_position <> actor_count - 1)) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is incomplete' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java new file mode 100644 index 0000000000..2c848fb966 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java @@ -0,0 +1,431 @@ +package net.firedevops.firemud.entitymanagement; + +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 java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterExecutionContext; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshot; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +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.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 CanonicalGameplayRosterIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "entity_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private CharacterRepository characterRepository; + @Autowired private JdbcTemplate jdbcTemplate; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + private UUID accountUuid; + private UUID tenantUuid; + private UUID realmUuid; + private UUID namespaceUuid; + + @BeforeEach + void createIsolatedTarget() { + accountUuid = UUID.randomUUID(); + tenantUuid = UUID.randomUUID(); + realmUuid = UUID.randomUUID(); + namespaceUuid = UUID.randomUUID(); + } + + @Test + void returnsOnlyFreshOwnerResolvedActorsForExactAccountTenantAndNamespace() { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + UUID selected = createPersistedActor(accountUuid, exactTarget, 41L, "Canonical Actor"); + createPersistedActor(UUID.randomUUID(), exactTarget, 42L, "Different Account Actor"); + CanonicalGameplayRosterTarget otherNamespaceTarget = + target(UUID.randomUUID(), exactTarget.gameInstanceUuid()); + UUID crossNamespace = + createPersistedActor(accountUuid, otherNamespaceTarget, 41L, "Other Namespace Actor"); + jdbcTemplate.update( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + + "VALUES (?, ?, ?, ?)", + 41L, + "Legacy numeric actor", + 71L, + "shared-live"); + + CanonicalGameplayRosterSnapshot roster = readRoster(accountUuid, exactTarget); + CanonicalGameplayRosterSnapshot otherNamespaceRoster = + readRoster(accountUuid, otherNamespaceTarget); + + assertThat(roster.target()).isEqualTo(exactTarget); + assertThat(roster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(selected, "Canonical Actor")); + assertThat(roster.actors()).noneMatch(actor -> actor.characterUuid().equals(crossNamespace)); + assertThat(otherNamespaceRoster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(crossNamespace, "Other Namespace Actor")); + + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + selected); + CanonicalGameplayRosterSnapshot afterQuarantine = readRoster(accountUuid, exactTarget); + assertThat(afterQuarantine.actors()).isEmpty(); + assertThat(afterQuarantine.snapshotDigest()).isNotEqualTo(roster.snapshotDigest()); + } + + @Test + void snapshotsPersistedPreseededDisplayNameAtOneHundredUnicodeCodePoints() { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + String displayName = "\uD83D\uDE00".repeat(100); + UUID characterUuid = createPersistedActor(accountUuid, exactTarget, 43L, displayName); + + CanonicalGameplayRosterSnapshot roster = readRoster(accountUuid, exactTarget); + + assertThat(roster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(characterUuid, displayName)); + } + + @Test + void reusesExactSnapshotAndChangesIdentityForRosterOrTargetChanges() { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + UUID actor = createPersistedActor(accountUuid, exactTarget, 51L, "Before Rename"); + + CanonicalGameplayRosterSnapshot first = readRoster(accountUuid, exactTarget); + CanonicalGameplayRosterSnapshot identical = readRoster(accountUuid, exactTarget); + assertThat(identical.snapshotUuid()).isEqualTo(first.snapshotUuid()); + assertThat(identical.snapshotDigest()).isEqualTo(first.snapshotDigest()); + CanonicalGameplayRosterSnapshotReference expectedReference = + new CanonicalGameplayRosterSnapshotReference(first.snapshotUuid(), first.snapshotDigest()); + assertThat( + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, exactTarget, expectedReference)) + .isEqualTo(first); + assertThatThrownBy( + () -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, + exactTarget, + new CanonicalGameplayRosterSnapshotReference( + UUID.randomUUID(), first.snapshotDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_UNAVAILABLE"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT canonical_version_uuid FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + UUID.class, + first.snapshotUuid())) + .isEqualTo(exactTarget.canonicalVersionUuid()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT publication_evidence_format FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + String.class, + first.snapshotUuid())) + .isEqualTo("CANONICAL_UUID_V2"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT pointer_version FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + Long.class, + first.snapshotUuid())) + .isEqualTo(exactTarget.pointerVersion()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT active_world_epoch FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + Long.class, + first.snapshotUuid())) + .isEqualTo(exactTarget.activeWorldEpoch()); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET canonical_version_uuid = ? WHERE snapshot_uuid = ?", + UUID.randomUUID(), + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET pointer_version = ? WHERE snapshot_uuid = ?", + exactTarget.pointerVersion() + 1, + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET active_world_epoch = ? WHERE snapshot_uuid = ?", + exactTarget.activeWorldEpoch() + 1, + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + + jdbcTemplate.update( + "UPDATE characters SET name = ? WHERE character_uuid = ?", "After Rename", actor); + CanonicalGameplayRosterSnapshot changedRoster = readRoster(accountUuid, exactTarget); + assertThat(changedRoster.snapshotUuid()).isNotEqualTo(first.snapshotUuid()); + assertThat(changedRoster.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); + assertThat(changedRoster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(actor, "After Rename")); + assertThatThrownBy( + () -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, exactTarget, expectedReference)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE"); + + CanonicalGameplayRosterTarget changedRuntimeFence = target(namespaceUuid, UUID.randomUUID()); + CanonicalGameplayRosterSnapshot changedTarget = readRoster(accountUuid, changedRuntimeFence); + assertThat(changedTarget.snapshotUuid()).isNotEqualTo(changedRoster.snapshotUuid()); + assertThat(changedTarget.snapshotDigest()).isNotEqualTo(changedRoster.snapshotDigest()); + + CanonicalGameplayRosterTarget changedPointer = + withCounters(exactTarget, exactTarget.pointerVersion() + 1, exactTarget.activeWorldEpoch()); + CanonicalGameplayRosterSnapshot changedPointerSnapshot = + readRoster(accountUuid, changedPointer); + assertThat(changedPointerSnapshot.snapshotUuid()).isNotEqualTo(first.snapshotUuid()); + assertThat(changedPointerSnapshot.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); + assertThat(changedPointerSnapshot.target().pointerVersion()) + .isEqualTo(changedPointer.pointerVersion()); + + CanonicalGameplayRosterTarget changedEpoch = + withCounters(exactTarget, exactTarget.pointerVersion(), exactTarget.activeWorldEpoch() + 1); + CanonicalGameplayRosterSnapshot changedEpochSnapshot = readRoster(accountUuid, changedEpoch); + assertThat(changedEpochSnapshot.snapshotUuid()).isNotEqualTo(first.snapshotUuid()); + assertThat(changedEpochSnapshot.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); + assertThat(changedEpochSnapshot.target().activeWorldEpoch()) + .isEqualTo(changedEpoch.activeWorldEpoch()); + + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET world_slug = 'changed' WHERE snapshot_uuid = ?", + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshot_actors " + + "SET display_name = 'tampered' " + + "WHERE snapshot_uuid = ? AND character_uuid = ?", + first.snapshotUuid(), + actor)) + .isInstanceOf(RuntimeException.class); + } + + @Test + void concurrentIdenticalReadsReuseOnePersistedSnapshotIdentity() throws Exception { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + createPersistedActor(accountUuid, exactTarget, 61L, "Concurrent Actor"); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + start.await(); + return readRoster(accountUuid, exactTarget); + }); + Future second = + executor.submit( + () -> { + start.await(); + return readRoster(accountUuid, exactTarget); + }); + start.countDown(); + + CanonicalGameplayRosterSnapshot firstResult = first.get(15, TimeUnit.SECONDS); + CanonicalGameplayRosterSnapshot secondResult = second.get(15, TimeUnit.SECONDS); + assertThat(secondResult.snapshotUuid()).isEqualTo(firstResult.snapshotUuid()); + assertThat(secondResult.snapshotDigest()).isEqualTo(firstResult.snapshotDigest()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_digest = ?", + Integer.class, + firstResult.snapshotDigest())) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private CanonicalGameplayRosterSnapshot readRoster( + UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + CanonicalGameplayRosterReadRequest request = + new CanonicalGameplayRosterReadRequest( + requestUuid, + canonicalAccountUuid, + target, + new CanonicalGameplayRosterExecutionContext( + canonicalAccountUuid, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + null, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope())); + return characterRepository.captureCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), canonicalAccountUuid, target, Instant.now())); + } + + private UUID createPersistedActor( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget target, + long accountRowId, + String displayName) { + UUID assignmentUuid = UUID.randomUUID(); + PreseededActorAssignmentOwnerEvidence ownerEvidence = + new PreseededActorAssignmentOwnerEvidence( + assignmentUuid, + canonicalAccountUuid, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 4L, + "1".repeat(64), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef()); + PreseededActorAssignmentRequest request = + new PreseededActorAssignmentRequest( + assignmentUuid, + canonicalAccountUuid, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, displayName), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + PreseededActorAssignmentResult result = + characterRepository.assignPreseededActor( + request, + ownerEvidence, + new RuntimeAccountIdentityEvidence( + 1, + "dev", + assignmentUuid, + canonicalAccountUuid, + accountRowId, + "ACCOUNT_DATABASE_INSERT"), + request.mutationIntentDigest()); + assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + return result.characterUuid(); + } + + private CanonicalGameplayRosterTarget target(UUID namespace, UUID instance) { + return new CanonicalGameplayRosterTarget( + tenantUuid, + realmUuid, + "world", + "realm", + instance, + 7L, + 13L, + 19L, + UUID.fromString("21000000-0000-4000-8000-000000000021"), + "3".repeat(64), + "release/roster-test", + "4".repeat(64), + "5".repeat(64), + namespace, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + } + + private CanonicalGameplayRosterTarget withCounters( + CanonicalGameplayRosterTarget target, long pointerVersion, long activeWorldEpoch) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + pointerVersion, + activeWorldEpoch, + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.entryPolicy()); + } +} 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 1ad440f8a1..4b1f58ada9 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,10 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; -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; @@ -16,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 +30,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 +42,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 = @@ -78,44 +65,18 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private ItemInstanceRepository itemInstanceRepository; @Autowired private ItemStackRepository itemStackRepository; @Autowired private ContainerInstanceRepository containerInstanceRepository; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; - @MockitoBean private ScopedCharacterResolver scopedCharacterResolver; @BeforeEach - void cleanDatabase() { - tenantId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); - 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 (!this.tenantId.equals(tenantId) - || !GAME_INSTANCE_ID.equals(gameInstanceId) - || PLAYABLE_STATE_SCOPE != playableStateScope - || character == null - || !this.tenantId.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)); + void allocateIsolatedFixtureTenant() { + tenantId = java.util.concurrent.ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); } @Test 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")); @@ -222,7 +183,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")); @@ -328,12 +288,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/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java new file mode 100644 index 0000000000..05a2b96b1c --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -0,0 +1,1168 @@ +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.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.dao.DataAccessException; +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 PreseededActorAssignmentIntegrationTest { + private UUID assignmentUuid; + private UUID secondAssignmentUuid; + private UUID accountUuid; + private UUID secondAccountUuid; + private UUID tenantUuid; + private UUID realmUuid; + private UUID namespaceUuid; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "entity_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private CharacterRepository characterRepository; + @Autowired private JdbcTemplate jdbcTemplate; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @BeforeEach + void createIsolatedOwnerProofIdentities() { + assignmentUuid = UUID.randomUUID(); + secondAssignmentUuid = UUID.randomUUID(); + accountUuid = UUID.randomUUID(); + secondAccountUuid = UUID.randomUUID(); + tenantUuid = UUID.randomUUID(); + realmUuid = UUID.randomUUID(); + namespaceUuid = UUID.randomUUID(); + } + + @Test + void postgresMigrationInstallsAndEnforcesDeferredAssignmentForeignKeys() { + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + + UUID missingCharacterUuid = UUID.randomUUID(); + UUID invalidOperationUuid = UUID.randomUUID(); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "INSERT INTO entity_preseeded_actor_assignment_operations (" + + "assignment_uuid, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, " + + "eligibility_evaluated_at, membership_authority_generation, " + + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " + + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " + + "publication_evidence_format, frozen_policy_digest, " + + "playable_state_namespace_id, playable_state_scope, entry_policy, " + + "actor_kind, display_name, status, character_uuid, completed_at, " + + "account_authority_snapshot_digest, account_purpose, account_currentness, " + + "published_owner_proof_digest, published_release_bundle_ref) " + + "SELECT ?, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, " + + "eligibility_evaluated_at, membership_authority_generation, " + + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " + + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " + + "publication_evidence_format, frozen_policy_digest, " + + "playable_state_namespace_id, playable_state_scope, entry_policy, " + + "actor_kind, display_name, 'ASSIGNED', ?, CURRENT_TIMESTAMP " + + ", account_authority_snapshot_digest, account_purpose, " + + "account_currentness, published_owner_proof_digest, " + + "published_release_bundle_ref " + + "FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + invalidOperationUuid, + missingCharacterUuid, + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + + assertThat( + jdbcTemplate.queryForList( + "SELECT conname FROM pg_constraint " + + "WHERE conname IN (?, ?, ?) AND contype = 'f' AND convalidated " + + "AND condeferrable AND condeferred " + + "AND conrelid = 'entity_preseeded_actor_assignment_operations'::regclass", + String.class, + "fk_entity_preseeded_assignment_tenant_identity", + "fk_entity_preseeded_assignment_namespace", + "fk_entity_preseeded_assignment_character")) + .containsExactlyInAnyOrder( + "fk_entity_preseeded_assignment_tenant_identity", + "fk_entity_preseeded_assignment_namespace", + "fk_entity_preseeded_assignment_character"); + } + + @Test + void migrationRetainsOlderRosterEvidenceWithoutBackfillingOwnerCounters() throws Exception { + String schema = "ph_" + UUID.randomUUID().toString().replace("-", ""); + UUID historicalSnapshot = UUID.randomUUID(); + UUID v8Snapshot = UUID.randomUUID(); + UUID historicalTenant = UUID.randomUUID(); + UUID historicalNamespace = UUID.randomUUID(); + UUID v8CanonicalVersion = UUID.randomUUID(); + + migrationFlyway(schema).target(MigrationVersion.fromVersion("1008")).load().migrate(); + try (Connection connection = connectToSchema(schema)) { + try (PreparedStatement tenant = + connection.prepareStatement( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)")) { + tenant.setObject(1, historicalTenant); + tenant.executeUpdate(); + } + try (PreparedStatement namespace = + connection.prepareStatement( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?)")) { + namespace.setObject(1, historicalTenant); + namespace.setObject(2, historicalNamespace); + namespace.setString(3, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + namespace.executeUpdate(); + } + try (PreparedStatement snapshot = + connection.prepareStatement( + "INSERT INTO entity_canonical_gameplay_roster_snapshots " + + "(snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, " + + "realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, " + + "published_version_id, published_version_number, published_policy_digest, " + + "published_release_bundle_ref, admission_pointer_snapshot_digest, " + + "published_owner_proof_digest, playable_state_namespace_uuid, " + + "playable_state_scope, entry_policy, roster_count, construction_state) " + + "VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 7, 17, 2, ?, " + + "'release/test', ?, ?, ?, ?, 'PRESEEDED_ONLY', 0, 'SEALED')")) { + snapshot.setObject(1, historicalSnapshot); + snapshot.setString(2, "a".repeat(64)); + snapshot.setObject(3, UUID.randomUUID()); + snapshot.setObject(4, historicalTenant); + snapshot.setObject(5, UUID.randomUUID()); + snapshot.setObject(6, UUID.randomUUID()); + snapshot.setString(7, "b".repeat(64)); + snapshot.setString(8, "c".repeat(64)); + snapshot.setString(9, "d".repeat(64)); + snapshot.setObject(10, historicalNamespace); + snapshot.setString(11, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + snapshot.executeUpdate(); + } + } + + migrationFlyway(schema).target(MigrationVersion.fromVersion("1009")).load().migrate(); + try (Connection connection = connectToSchema(schema); + PreparedStatement snapshot = + connection.prepareStatement( + "INSERT INTO entity_canonical_gameplay_roster_snapshots " + + "(snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, " + + "realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, " + + "published_version_id, published_version_number, canonical_version_uuid, " + + "publication_evidence_format, published_policy_digest, " + + "published_release_bundle_ref, admission_pointer_snapshot_digest, " + + "published_owner_proof_digest, playable_state_namespace_uuid, " + + "playable_state_scope, entry_policy, roster_count, construction_state) " + + "VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 7, NULL, NULL, ?, " + + "'CANONICAL_UUID', ?, 'release/v8', ?, ?, ?, ?, " + + "'PRESEEDED_ONLY', 0, 'SEALED')")) { + snapshot.setObject(1, v8Snapshot); + snapshot.setString(2, "e".repeat(64)); + snapshot.setObject(3, UUID.randomUUID()); + snapshot.setObject(4, historicalTenant); + snapshot.setObject(5, UUID.randomUUID()); + snapshot.setObject(6, UUID.randomUUID()); + snapshot.setObject(7, v8CanonicalVersion); + snapshot.setString(8, "f".repeat(64)); + snapshot.setString(9, "a".repeat(64)); + snapshot.setString(10, "b".repeat(64)); + snapshot.setObject(11, historicalNamespace); + snapshot.setString(12, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + snapshot.executeUpdate(); + } + + migrationFlyway(schema).load().migrate(); + try (Connection connection = connectToSchema(schema); + PreparedStatement retained = + connection.prepareStatement( + "SELECT snapshot_digest, publication_evidence_format, canonical_version_uuid, " + + "published_version_id, published_version_number, pointer_version, " + + "active_world_epoch " + + "FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?")) { + retained.setObject(1, historicalSnapshot); + try (ResultSet row = retained.executeQuery()) { + assertThat(row.next()).isTrue(); + assertThat(row.getString(1)).isEqualTo("a".repeat(64)); + assertThat(row.getString(2)).isEqualTo("LEGACY_NUMERIC"); + assertThat(row.getObject(3)).isNull(); + assertThat(row.getLong(4)).isEqualTo(17L); + assertThat(row.getInt(5)).isEqualTo(2); + assertThat(row.getObject(6)).isNull(); + assertThat(row.getObject(7)).isNull(); + } + } + try (Connection connection = connectToSchema(schema); + PreparedStatement retained = + connection.prepareStatement( + "SELECT snapshot_digest, publication_evidence_format, canonical_version_uuid, " + + "published_version_id, published_version_number, pointer_version, " + + "active_world_epoch " + + "FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?")) { + retained.setObject(1, v8Snapshot); + try (ResultSet row = retained.executeQuery()) { + assertThat(row.next()).isTrue(); + assertThat(row.getString(1)).isEqualTo("e".repeat(64)); + assertThat(row.getString(2)).isEqualTo("CANONICAL_UUID"); + assertThat(row.getObject(3)).isEqualTo(v8CanonicalVersion); + assertThat(row.getObject(4)).isNull(); + assertThat(row.getObject(5)).isNull(); + assertThat(row.getObject(6)).isNull(); + assertThat(row.getObject(7)).isNull(); + } + } + } + + @Test + void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace() + throws Exception { + String schema = "pa_" + UUID.randomUUID().toString().replace("-", ""); + UUID retainedAccountUuid = UUID.randomUUID(); + UUID retainedTenantUuid = UUID.randomUUID(); + UUID retainedNamespaceUuid = UUID.randomUUID(); + + migrationFlyway(schema).target(MigrationVersion.fromVersion("1005")).load().migrate(); + List parentHistory = appliedMigrationHistory(schema); + assertThat(parentHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); + assertThat(parentHistory) + .extracting(AppliedMigration::version) + .containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005"); + assertThat(parentHistory) + .extracting(AppliedMigration::script) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql", + "V1003__quarantine_unresolved_actor_identity.sql", + "V1004__build_actor_identity_indexes_concurrently.sql", + "V1005__validate_actor_identity_constraints.sql"); + assertThat(parentHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); + try (Connection connection = connectToSchema(schema)) { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?)")) { + statement.setObject(1, retainedTenantUuid); + statement.setObject(2, retainedNamespaceUuid); + statement.setString(3, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + statement.executeUpdate(); + } + try (PreparedStatement statement = + connection.prepareStatement( + "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 (23, ?, 41, ?, ?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL)")) { + for (String retainedName : List.of("Retained duplicate A", "Retained duplicate B")) { + statement.setString(1, retainedName); + statement.setString(2, retainedNamespaceUuid.toString()); + statement.setObject(3, UUID.randomUUID()); + statement.setObject(4, retainedAccountUuid); + statement.setObject(5, retainedTenantUuid); + statement.setObject(6, retainedNamespaceUuid); + statement.setString(7, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + statement.executeUpdate(); + } + } + } + + migrationFlyway(schema).load().migrate(); + + List upgradedHistory = appliedMigrationHistory(schema); + assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); + assertThat(upgradedHistory.subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + List successorHistory = + upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); + assertThat(successorHistory) + .extracting(AppliedMigration::version) + .containsExactly("1006", "1007", "1008", "1009", "1010"); + assertThat(successorHistory) + .extracting(AppliedMigration::script) + .containsExactly( + "V1006__preseeded_actor_assignment.sql", + "V1007__preseeded_assignment_owner_snapshot.sql", + "V1008__canonical_gameplay_roster_snapshots.sql", + "V1009__canonical_publication_uuid_actor_evidence.sql", + "V1010__canonical_roster_owner_counters.sql"); + assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); + + try (Connection connection = connectToSchema(schema)) { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FROM characters WHERE account_uuid = ? " + + "AND actor_identity_status = 'QUARANTINED' " + + "AND actor_identity_quarantine_reason = 'AMBIGUOUS_ACCOUNT_NAMESPACE'")) { + statement.setObject(1, retainedAccountUuid); + try (ResultSet rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isEqualTo(2L); + } + } + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FROM pg_indexes WHERE schemaname = ? " + + "AND indexname = 'ux_characters_owner_resolved_account_namespace'")) { + statement.setString(1, schema); + try (ResultSet rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isEqualTo(1L); + } + } + try (PreparedStatement insert = + connection.prepareStatement( + "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 (23, 'New verified assignment', 41, ?, ?, ?, ?, ?, ?, " + + "'OWNER_RESOLVED', NULL)")) { + insert.setString(1, retainedNamespaceUuid.toString()); + insert.setObject(2, UUID.randomUUID()); + insert.setObject(3, retainedAccountUuid); + insert.setObject(4, retainedTenantUuid); + insert.setObject(5, retainedNamespaceUuid); + insert.setString(6, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + assertThat(insert.executeUpdate()).isEqualTo(1); + } + try (PreparedStatement duplicate = + connection.prepareStatement( + "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 (23, 'Duplicate live actor', 41, ?, ?, ?, ?, ?, ?, " + + "'OWNER_RESOLVED', NULL)")) { + duplicate.setString(1, retainedNamespaceUuid.toString()); + duplicate.setObject(2, UUID.randomUUID()); + duplicate.setObject(3, retainedAccountUuid); + duplicate.setObject(4, retainedTenantUuid); + duplicate.setObject(5, retainedNamespaceUuid); + duplicate.setString(6, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + assertThatThrownBy(duplicate::executeUpdate).isInstanceOf(SQLException.class); + } + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FILTER (WHERE actor_identity_status = 'QUARANTINED'), " + + "count(*) FILTER (WHERE actor_identity_status = 'OWNER_RESOLVED') " + + "FROM characters WHERE account_uuid = ?")) { + statement.setObject(1, retainedAccountUuid); + try (ResultSet rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isEqualTo(2L); + assertThat(rows.getLong(2)).isEqualTo(1L); + } + } + } + } + + @Test + void exactRetryReturnsSamePersistedActorAndChangedIntentConflictsBeforeAllocation() { + PreseededActorAssignmentResult first = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + PreseededActorAssignmentResult retry = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + PreseededActorAssignmentResult changedIntent = + assign( + assignmentUuid, + accountUuid, + 5L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "b"); + + assertThat(first.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(retry).isEqualTo(first); + assertThat(retry.characterUuid()).isEqualTo(first.characterUuid()); + assertConflictWithoutActorDisclosure(changedIntent); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE character_uuid = ? " + + "AND account_uuid = ? AND tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + first.characterUuid(), + accountUuid, + tenantUuid, + namespaceUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + Integer.class, + assignmentUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters c " + + "JOIN entity_tenant_identities t " + + "ON c.tenant_id = t.entity_tenant_row_id " + + "WHERE c.character_uuid = ? AND t.canonical_tenant_uuid = ?", + Integer.class, + first.characterUuid(), + tenantUuid)) + .isEqualTo(1); + } + + @Test + void committedReceiptIsExactReplayStableAndDeniedForChangedOrQuarantinedActor() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + var evidence = + evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + var expectedTarget = + new PreseededActorAssignmentExpectedTarget( + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + namespaceUuid, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + var exactRequest = + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + expectedTarget); + + var receipt = + characterRepository.readPreseededActorAssignmentReceipt(exactRequest).orElseThrow(); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(exactRequest)) + .contains(receipt); + assertThat(receipt.assignmentUuid()).isEqualTo(assignmentUuid); + assertThat(receipt.canonicalAccountUuid()).isEqualTo(accountUuid); + assertThat(receipt.characterUuid()).isEqualTo(assigned.characterUuid()); + assertThat(receipt.intentDigest()).isEqualTo(assigned.intentDigest()); + assertThat(receipt.target()).isEqualTo(expectedTarget); + assertThat(receipt.accountPurpose()) + .isEqualTo(PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING); + assertThat(receipt.accountCurrentness()) + .isEqualTo( + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION); + assertThat(receipt.accountIdentitySchemaVersion()).isEqualTo(1); + assertThat(receipt.accountIdentityTargetNamespace()).isEqualTo("dev"); + assertThat(receipt.sourceAccountRowId()).isEqualTo(23L); + assertThat(receipt.accountUuidProvenance()).isEqualTo("ACCOUNT_DATABASE_INSERT"); + assertThat(receipt.eligibility()) + .isEqualTo(PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE); + assertThat(receipt.eligibleAtRevalidation()).isTrue(); + assertThat(receipt.publishedReleaseBundleRef()).isEqualTo("release-bundle/test"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT canonical_version_uuid FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + UUID.class, + assignmentUuid)) + .isEqualTo(expectedTarget.canonicalVersionUuid()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT publication_evidence_format FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + String.class, + assignmentUuid)) + .isEqualTo("CANONICAL_UUID"); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_preseeded_actor_assignment_operations " + + "SET canonical_version_uuid = ? WHERE assignment_uuid = ?", + UUID.randomUUID(), + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + "f".repeat(64), + expectedTarget))) + .isEmpty(); + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + secondAccountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + expectedTarget))) + .isEmpty(); + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + UUID.randomUUID(), + assigned.intentDigest(), + expectedTarget))) + .isEmpty(); + + jdbcTemplate.update( + "UPDATE characters SET account_id = 24 WHERE character_uuid = ?", assigned.characterUuid()); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(exactRequest)).isEmpty(); + jdbcTemplate.update( + "UPDATE characters SET account_id = 23 WHERE character_uuid = ?", assigned.characterUuid()); + + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + assigned.characterUuid()); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(exactRequest)).isEmpty(); + + PreseededActorAssignmentOwnerEvidence changedReleaseRef = + withPublishedReleaseBundleRef(evidence, "release-bundle/changed"); + PreseededActorAssignmentRequest replayRequest = assignmentRequest(changedReleaseRef); + PreseededActorAssignmentResult changedRelease = + characterRepository.assignPreseededActor( + replayRequest, + changedReleaseRef, + accountIdentity(assignmentUuid, accountUuid), + replayRequest.mutationIntentDigest()); + assertConflictWithoutActorDisclosure(changedRelease); + } + + @Test + void selectedAssignmentReadRequiresExactOwnerTargetAndCurrentActorProvenance() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Selected Actor", + "a"); + var ownerEvidence = + evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + var expectedTarget = assignmentRequest(ownerEvidence).expectedTarget(); + + var receipt = + characterRepository + .readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest()) + .orElseThrow(); + assertThat(receipt.assignmentUuid()).isEqualTo(assignmentUuid); + assertThat(receipt.canonicalAccountUuid()).isEqualTo(accountUuid); + assertThat(receipt.characterUuid()).isEqualTo(assigned.characterUuid()); + assertThat(receipt.intentDigest()).isEqualTo(assigned.intentDigest()); + + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + secondAccountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + UUID.randomUUID(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + new PreseededActorAssignmentExpectedTarget( + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + 5L, + expectedTarget.canonicalVersionUuid(), + expectedTarget.frozenPolicyDigest(), + namespaceUuid, + expectedTarget.publishedReleaseBundleRef(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + new PreseededActorAssignmentExpectedTarget( + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + 4L, + expectedTarget.canonicalVersionUuid(), + expectedTarget.frozenPolicyDigest(), + namespaceUuid, + expectedTarget.publishedReleaseBundleRef(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED), + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, assigned.characterUuid(), expectedTarget, "f".repeat(64))) + .isEmpty(); + + jdbcTemplate.update( + "UPDATE characters SET account_uuid = ? WHERE character_uuid = ?", + secondAccountUuid, + assigned.characterUuid()); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + jdbcTemplate.update( + "UPDATE characters SET account_uuid = ? WHERE character_uuid = ?", + accountUuid, + assigned.characterUuid()); + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + assigned.characterUuid()); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + } + + @Test + void sameAssignmentUuidConflictsForChangedAccountScopeOrPayloadWithoutReturningActor() { + PreseededActorAssignmentResult original = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + PreseededActorAssignmentResult changedAccount = + assign( + assignmentUuid, + secondAccountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "b"); + PreseededActorAssignmentResult changedScope = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + "Assigned Actor", + "c"); + PreseededActorAssignmentResult changedPayload = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Renamed Actor", + "d"); + + assertThat(original.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertConflictWithoutActorDisclosure(changedAccount); + assertConflictWithoutActorDisclosure(changedScope); + assertConflictWithoutActorDisclosure(changedPayload); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE actor_identity_status = 'OWNER_RESOLVED' " + + "AND tenant_uuid = ?", + Integer.class, + tenantUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ? AND status = 'ASSIGNED'", + Integer.class, + assignmentUuid)) + .isEqualTo(1); + } + + @Test + void separateAuthorizedAssignmentsCanCreateMultipleActorsEvenWithSameDisplayName() { + PreseededActorAssignmentResult first = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + PreseededActorAssignmentResult second = + assign( + secondAssignmentUuid, + secondAccountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "b"); + + assertThat(first.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(second.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(second.characterUuid()).isNotEqualTo(first.characterUuid()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND account_uuid = ? " + + "AND name = 'Assigned Actor' AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + tenantUuid, + namespaceUuid, + accountUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND account_uuid = ? " + + "AND name = 'Assigned Actor' AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + tenantUuid, + namespaceUuid, + secondAccountUuid)) + .isEqualTo(1); + } + + @Test + void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Assignment race did not start"); + } + return assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor", + "a"); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Assignment race did not start"); + } + return assign( + secondAssignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor", + "b"); + }); + + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List results = + List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + PreseededActorAssignmentResult winner = + results.stream() + .filter(result -> result.outcome() == PreseededActorAssignmentResult.Outcome.ASSIGNED) + .findFirst() + .orElseThrow(); + PreseededActorAssignmentResult loser = + results.stream() + .filter( + result -> + result.outcome() + == PreseededActorAssignmentResult.Outcome.IDEMPOTENCY_CONFLICT) + .findFirst() + .orElseThrow(); + + assertThat(winner.characterUuid()).isNotNull(); + assertThat(loser.characterUuid()).isNull(); + assertThat( + assign( + loser.assignmentUuid(), + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor", + "retry")) + .isEqualTo(loser); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ? AND status = 'IDEMPOTENCY_CONFLICT' " + + "AND character_uuid IS NULL " + + "AND completed_at IS NOT NULL", + Integer.class, + loser.assignmentUuid())) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND account_uuid = ? " + + "AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + tenantUuid, + namespaceUuid, + accountUuid)) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void conflictingNamespaceScopeProofRollsBackGuardAndDoesNotPromoteOrAllocateActor() { + jdbcTemplate.update( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?)", + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED.name()); + + assertThatThrownBy( + () -> + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a")) + .isInstanceOf(RuntimeException.class); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ?", Integer.class, tenantUuid)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + Integer.class, + assignmentUuid)) + .isZero(); + } + + @Test + void assignmentReplayAndOwnerMappingsRejectDeleteAndTruncate() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", + tenantUuid)) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + jdbcTemplate.execute( + "TRUNCATE TABLE entity_preseeded_actor_assignment_operations CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE entity_tenant_identities")) + .isInstanceOf(DataAccessException.class); + + assertThat( + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a")) + .isEqualTo(assigned); + } + + private PreseededActorAssignmentResult assign( + UUID operationUuid, + UUID actorAccountUuid, + long catalogRevision, + PlayableStateScope scope, + String displayName, + String digestFirstHexDigit) { + PreseededActorAssignmentOwnerEvidence target = + evidence(operationUuid, actorAccountUuid, catalogRevision, scope); + PreseededActorAssignmentRequest request = assignmentRequest(target, displayName); + return characterRepository.assignPreseededActor( + request, + target, + accountIdentity(operationUuid, actorAccountUuid), + request.mutationIntentDigest()); + } + + private PreseededActorAssignmentRequest assignmentRequest( + PreseededActorAssignmentOwnerEvidence target) { + return assignmentRequest(target, "Assigned Actor"); + } + + private PreseededActorAssignmentRequest assignmentRequest( + PreseededActorAssignmentOwnerEvidence target, String displayName) { + return new PreseededActorAssignmentRequest( + target.assignmentUuid(), + target.canonicalAccountUuid(), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, displayName), + new PreseededActorAssignmentExpectedTarget( + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + "game-instance", + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + } + + private static PreseededActorAssignmentOwnerEvidence withPublishedReleaseBundleRef( + PreseededActorAssignmentOwnerEvidence evidence, String releaseRef) { + return new PreseededActorAssignmentOwnerEvidence( + evidence.assignmentUuid(), + evidence.canonicalAccountUuid(), + evidence.eligibility(), + evidence.eligibilityEvaluatedAt(), + evidence.membershipAuthorityGeneration(), + evidence.eligibilityEvidenceDigest(), + evidence.canonicalTenantUuid(), + evidence.realmUuid(), + evidence.worldSlug(), + evidence.realmSlug(), + "game-instance", + evidence.catalogRevision(), + evidence.canonicalVersionUuid(), + evidence.frozenPolicyDigest(), + evidence.playableStateNamespaceId(), + evidence.playableStateScope(), + evidence.entryPolicy(), + evidence.accountPurpose(), + evidence.accountCurrentness(), + evidence.accountAuthoritySnapshotDigest(), + evidence.publishedOwnerProofDigest(), + releaseRef); + } + + private PreseededActorAssignmentOwnerEvidence evidence( + UUID operationUuid, UUID actorAccountUuid, long catalogRevision, PlayableStateScope scope) { + return new PreseededActorAssignmentOwnerEvidence( + operationUuid, + actorAccountUuid, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 9L, + "1".repeat(64), + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + catalogRevision, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + namespaceUuid, + scope, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "3".repeat(64), + "4".repeat(64), + "release-bundle/test"); + } + + private RuntimeAccountIdentityEvidence accountIdentity(UUID requestUuid, UUID actorAccountUuid) { + return new RuntimeAccountIdentityEvidence( + 1, + "dev", + requestUuid, + actorAccountUuid, + actorAccountUuid.equals(accountUuid) ? 23L : 24L, + "ACCOUNT_DATABASE_INSERT"); + } + + private void assertConflictWithoutActorDisclosure(PreseededActorAssignmentResult result) { + assertThat(result.outcome()) + .isEqualTo(PreseededActorAssignmentResult.Outcome.IDEMPOTENCY_CONFLICT); + assertThat(result.characterUuid()).isNull(); + } + + private FluentConfiguration migrationFlyway(String schema) { + assertThat(("flyway_schema_history_" + schema + "_s_idx").length()).isLessThanOrEqualTo(63); + FluentConfiguration configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .table("flyway_schema_history_" + schema) + .outOfOrder(false) + .placeholders(Map.of("serviceSchema", schema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration; + } + + private List appliedMigrationHistory(String schema) throws SQLException { + List migrations = new ArrayList<>(); + try (Connection connection = connectToSchema(schema); + Statement statement = connection.createStatement(); + ResultSet rows = + statement.executeQuery( + "SELECT installed_rank, version, script, checksum, success FROM flyway_schema_history_" + + schema + + " WHERE version IS NOT NULL ORDER BY installed_rank")) { + while (rows.next()) { + migrations.add( + new AppliedMigration( + rows.getInt(1), + rows.getString(2), + rows.getString(3), + rows.getObject(4, Integer.class), + rows.getBoolean(5))); + } + } + return migrations; + } + + private record AppliedMigration( + int installedRank, String version, String script, Integer checksum, boolean success) {} + + private Connection connectToSchema(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO " + schema); + return connection; + } catch (SQLException failure) { + connection.close(); + throw failure; + } + } +} 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 58096b6170..a3800911d8 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 @@ -6,7 +6,6 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; -import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -14,18 +13,8 @@ import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; 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.InventoryService; -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 net.firedevops.firemud.test.TestContainerImages; @@ -36,7 +25,6 @@ import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.Timeout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -64,7 +52,6 @@ class RetainedActorIdentityIntegrationTest { private UUID tenantUuid; private UUID accountUuid; private UUID namespaceUuid; - private long fixtureIdOffset; private String testServiceSchema; @Container @@ -84,23 +71,14 @@ static void configure(DynamicPropertyRegistry registry) { 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 InventoryService inventoryService; - @Autowired private ScopedCharacterResolver scopedCharacterResolver; - @Autowired private CharacterService characterService; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private Flyway flyway; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @BeforeEach - void allocateIsolatedFixtureIdentities(TestInfo testInfo) { - fixtureIdOffset = fixtureIdOffset(testInfo.getTestMethod().orElseThrow().getName()); + void allocateIsolatedFixtureIdentities() { tenantId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); accountId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); instanceId = "GI-RETAINED-" + UUID.randomUUID(); @@ -109,30 +87,63 @@ void allocateIsolatedFixtureIdentities(TestInfo testInfo) { namespaceUuid = UUID.randomUUID(); } - private long fixtureIdOffset(String testMethodName) { - return switch (testMethodName) { - case "canonicalRosterMatchesExactOwnerIdentityAndExcludesLegacyQuarantine" -> 100_000L; - case "namespaceIdentityAndScopeAreImmutableWithoutActorReferences" -> 200_000L; - case "quarantinedActorLookupMutationExpiryAndCleanupRemainHeld" -> 300_000L; - case "destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows" -> 400_000L; - case "destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows" -> 500_000L; - case "unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping" -> 600_000L; - case "flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints" -> 700_000L; - case "characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch" -> 800_000L; - case "freshDefaultFlywayInstallsCompleteCombinedManifest" -> 900_000L; - default -> throw new IllegalArgumentException("No fixture ID range for " + testMethodName); - }; - } - - private long fixtureId(long localId) { - return fixtureIdOffset + localId; + @Test + void legacySaveAllocatesQuarantinedUuidAndPreservesLegacyReadbackAndUpdates() { + Character actor = new Character(); + actor.setTenantId(tenantId); + actor.setAccountId(accountId); + actor.setPlayableStateKey("instance:" + instanceId); + actor.setName("Retained actor"); + actor.setExperience(17); + actor = characterRepository.save(actor); + long actorId = actor.getId(); + UUID characterUuid = actor.getActorIdentity().characterUuid(); + assertThat(characterUuid).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(actor.getActorIdentity().status().name()).isEqualTo("QUARANTINED"); + assertThat(actor.getActorIdentity().quarantineReason()).isEqualTo("OWNER_PROVENANCE_MISSING"); + assertThat(actor.getActorIdentity().accountUuid()).isNull(); + assertThat(actor.getActorIdentity().tenantUuid()).isNull(); + assertThat(actor.getActorIdentity().playableStateNamespaceId()).isNull(); + assertThat(actor.getActorIdentity().playableStateScope()).isNull(); + assertThat(characterRepository.findById(actorId)).isPresent(); + assertThat(characterRepository.findWithInventoryById(actorId)).isPresent(); + assertThat(characterRepository.findByIdAndTenantId(actorId, tenantId)).isPresent(); + assertThat( + characterRepository.findByIdAndTenantIdAndPlayableStateKey( + actorId, tenantId, actor.getPlayableStateKey())) + .isPresent(); + assertThat( + characterRepository + .findByTenantIdAndAccountIdAndPlayableStateKey( + tenantId, accountId, actor.getPlayableStateKey(), null) + .getContent()) + .extracting(Character::getId) + .containsExactly(actorId); + assertThat( + characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( + tenantId, actor.getPlayableStateKey(), "retained ACTOR")) + .isPresent(); + + int originalVersion = actor.getVersion(); + actor.setName("Retained actor updated"); + actor.setExperience(18); + Character saved = characterRepository.save(actor); + assertThat(saved.getName()).isEqualTo("Retained actor updated"); + assertThat(saved.getExperience()).isEqualTo(18); + assertThat(saved.getVersion()).isEqualTo(originalVersion + 1); + assertThat(saved.getActorIdentity()).isEqualTo(actor.getActorIdentity()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT character_uuid FROM characters WHERE id = ?", UUID.class, actorId)) + .isEqualTo(characterUuid); } @Test - void canonicalRosterMatchesExactOwnerIdentityAndExcludesLegacyQuarantine() { + void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { + // SQL fixtures prove storage isolation only; they provide no owner authority or runtime + // admission. insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); UUID legacyActorUuid = UUID.randomUUID(); - UUID ownerResolvedActorUuid = UUID.randomUUID(); long legacyId = insertActor( "legacy-shared", @@ -146,124 +157,100 @@ void canonicalRosterMatchesExactOwnerIdentityAndExcludesLegacyQuarantine() { "OWNER_PROVENANCE_MISSING", accountId, tenantId); - + UUID resolvedActorUuid = UUID.randomUUID(); + long resolvedId = + insertActor( + "owner-resolved", + resolvedActorUuid, + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - accountUuid.toString(), - namespaceUuid.toString(), + storedActorUuids( + tenantUuid, + accountUuid, + namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isEmpty(); - assertThat(characterRepository.findByIdAndTenantId(legacyId, tenantId)).isEmpty(); - - insertActor( - "owner-resolved", - ownerResolvedActorUuid, - accountUuid, - tenantUuid, - namespaceUuid, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - accountId, - tenantId); - var roster = - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - accountUuid.toString(), - namespaceUuid.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - assertThat(roster) - .extracting(identity -> identity.characterUuid()) - .containsExactly(ownerResolvedActorUuid); - assertThat( - actorIdentityRepository.findOwnerResolvedActor( - tenantUuid.toString(), - accountUuid.toString(), - namespaceUuid.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - ownerResolvedActorUuid.toString())) - .get() - .extracting(identity -> identity.characterUuid()) - .isEqualTo(ownerResolvedActorUuid); - + .containsExactly(resolvedActorUuid); assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - UUID.randomUUID().toString(), - accountUuid.toString(), - namespaceUuid.toString(), + storedActorUuids( + UUID.randomUUID(), + accountUuid, + namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .isEmpty(); assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - UUID.randomUUID().toString(), - namespaceUuid.toString(), + storedActorUuids( + tenantUuid, + UUID.randomUUID(), + namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .isEmpty(); assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - accountUuid.toString(), - UUID.randomUUID().toString(), + storedActorUuids( + tenantUuid, + accountUuid, + UUID.randomUUID(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .isEmpty(); assertThat( - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - accountUuid.toString(), - namespaceUuid.toString(), + storedActorUuids( + tenantUuid, + accountUuid, + namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .isEmpty(); - assertThat( - actorIdentityRepository.findOwnerResolvedActor( - tenantUuid.toString(), - accountUuid.toString(), - namespaceUuid.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - legacyActorUuid.toString())) - .isEmpty(); - + Character resolved = characterRepository.findById(resolvedId).orElseThrow(); + assertThat(resolved.getActorIdentity().characterUuid()).isEqualTo(resolvedActorUuid); + assertThat(resolved.getActorIdentity().accountUuid()).isEqualTo(accountUuid); + assertThat(resolved.getActorIdentity().tenantUuid()).isEqualTo(tenantUuid); + assertThat(resolved.getActorIdentity().playableStateNamespaceId()).isEqualTo(namespaceUuid); + assertThat(resolved.getActorIdentity().playableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(resolved.getActorIdentity().status().name()).isEqualTo("OWNER_RESOLVED"); + assertThat( + characterRepository.findById(legacyId).orElseThrow().getActorIdentity().status().name()) + .isEqualTo("QUARANTINED"); assertThatThrownBy( () -> - actorIdentityRepository.findOwnerResolvedRoster( + insertActor( + "duplicate UUID", + resolvedActorUuid, null, - accountUuid.toString(), - namespaceUuid.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - accountUuid.toString(), - "not-a-uuid", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), - "00000000-0000-0000-0000-000000000000", - namespaceUuid.toString(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .isInstanceOf(IllegalArgumentException.class); - + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId)) + .isInstanceOf(RuntimeException.class); assertThatThrownBy( () -> insertNamespace( tenantUuid, namespaceUuid, 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(), - tenantUuid, - namespaceUuid)) - .isInstanceOf(RuntimeException.class); + } + + private List storedActorUuids( + UUID tenantUuid, UUID accountUuid, UUID namespaceUuid, PlayableStateScope scope) { + return jdbcTemplate.queryForList( + "SELECT character_uuid FROM characters WHERE tenant_uuid = ? AND account_uuid = ? " + + "AND playable_state_namespace_id = ? AND playable_state_scope = ? " + + "AND actor_identity_status = 'OWNER_RESOLVED' " + + "AND actor_identity_quarantine_reason IS NULL ORDER BY character_uuid", + UUID.class, + tenantUuid, + accountUuid, + namespaceUuid, + scope.name()); } @Test @@ -332,497 +319,6 @@ void namespaceIdentityAndScopeAreImmutableWithoutActorReferences() { } } - @Test - void quarantinedActorLookupMutationExpiryAndCleanupRemainHeld() { - Character actor = new Character(); - actor.setTenantId(tenantId); - actor.setAccountId(accountId); - actor.setPlayableStateKey("instance:" + instanceId); - 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(tenantId); - resourceWrite.setCharacterId(actorId); - resourceWrite.setPlayableStateKey("instance:" + instanceId); - 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(tenantId); - conditionWrite.setCharacterId(actorId); - conditionWrite.setPlayableStateKey("instance:" + instanceId); - 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 " - + "(" - + fixtureId(3001) - + ", 'Backpack', ?, true), (" - + fixtureId(3002) - + ", 'Pouch', ?, true), (" - + fixtureId(3003) - + ", 'Gem', ?, false)", - tenantId, - tenantId, - tenantId); - jdbcTemplate.update( - "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (?, " - + fixtureId(3003) - + ", 5, 2)", - actorId); - jdbcTemplate.update( - "INSERT INTO character_equipment (character_id, slot, item_id, version) " - + "VALUES (?, 'hand', " - + fixtureId(3003) - + ", 3)", - actorId); - jdbcTemplate.update( - "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) " - + "VALUES (?, ?, ?, 'pending')", - actorId, - actorId, - tenantId); - 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)", - tenantId, - actorId, - "instance:" + instanceId); - 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)", - tenantId, - actorId, - "instance:" + instanceId); - - jdbcTemplate.update( - "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) " - + "VALUES (" - + fixtureId(3101) - + ", ?, ?, ?, " - + fixtureId(3001) - + ", 6)", - tenantId, - actorId, - instanceId); - insertItemInstance( - fixtureId(3201), actorId, instanceId, null, fixtureId(3001), "retained-backpack"); - jdbcTemplate.update( - "UPDATE container_instances SET item_instance_id = ? WHERE id = ?", - fixtureId(3201), - fixtureId(3101)); - insertItemInstance( - fixtureId(3202), null, instanceId, fixtureId(3101), fixtureId(3002), "retained-pouch"); - jdbcTemplate.update( - "INSERT INTO container_instances (id, tenant_id, game_instance_id, item_id, version, item_instance_id) " - + "VALUES (" - + fixtureId(3102) - + ", ?, ?, " - + fixtureId(3002) - + ", 7, " - + fixtureId(3202) - + ")", - tenantId, - instanceId); - insertItemInstance( - fixtureId(3203), null, instanceId, fixtureId(3102), fixtureId(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 (" - + fixtureId(3301) - + ", ?, ?, ?, " - + fixtureId(3003) - + ", 'actor-stack', 8, 2, 'actor-family')", - tenantId, - actorId, - instanceId); - 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 (" - + fixtureId(3302) - + ", ?, ?, " - + fixtureId(3102) - + ", " - + fixtureId(3003) - + ", 'nested-stack', 9, 3, 'nested-family')", - tenantId, - instanceId); - jdbcTemplate.update( - "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " - + "VALUES (?, ?, 'room-retained', " - + fixtureId(3003) - + ", 11, 8)", - tenantId, - instanceId); - 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 (" - + fixtureId(3401) - + ", ?, " - + fixtureId(3001) - + ", " - + fixtureId(3201) - + ", 1, 'DROP', ?, 'effect-retained', 'corr-retained', 'CHARACTER', ?, ?, 'ROOM', ?, 'room-retained')", - tenantId, - actorId, - actorId, - instanceId, - instanceId); - jdbcTemplate.update( - "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) " - + "VALUES (" - + fixtureId(3501) - + ", ?, 'effect-retained', 'DROP', 'DropResponse', decode('aabb', 'hex'), 'APPLIED')", - tenantId); - - assertThatThrownBy( - () -> - scopedCharacterResolver.requireScopedCharacter( - tenantId, - actorId, - instanceId, - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); - Map holderCountsBeforeRejectedAdd = inventoryHolderMutationCounts(actorId); - assertThatThrownBy( - () -> - inventoryService.addItem( - tenantId, - actorId, - instanceId, - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, - fixtureId(3001), - 1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("OWNER_RESOLVED_ACTOR_IDENTITY_REQUIRED"); - assertThat(inventoryHolderMutationCounts(actorId)).isEqualTo(holderCountsBeforeRejectedAdd); - assertThatThrownBy( - () -> - characterService.gainExperience( - tenantId, - actorId, - instanceId, - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, - 100)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - runtimeInstanceCleanupService.cleanupRuntimeInstance( - tenantId, instanceId, "termination-retained")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP"); - - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - tenantId, instanceId)) - .isTrue(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM entity_quarantined_actor_item_instances WHERE tenant_id = ?", - Integer.class, - tenantId)) - .isEqualTo(3); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM entity_quarantined_actor_container_instances WHERE tenant_id = ?", - Integer.class, - tenantId)) - .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 = ?", - Integer.class, - actorId, - fixtureId(3003))) - .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, - tenantId, - instanceId)) - .isEqualTo(3); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - instanceId)) - .isEqualTo(2); - assertThat( - jdbcTemplate.queryForObject( - "SELECT sum(quantity) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - instanceId)) - .isEqualTo(17); - assertThat( - jdbcTemplate.queryForObject( - "SELECT quantity FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - instanceId)) - .isEqualTo(11); - assertThat( - jdbcTemplate.queryForObject( - "SELECT correlation_key FROM item_transfer_audits WHERE id = ?", - String.class, - fixtureId(3401))) - .isEqualTo("corr-retained"); - assertThat( - jdbcTemplate.queryForObject( - "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = ?", - String.class, - fixtureId(3501))) - .isEqualTo("aabb"); - } - - @Test - void destinationOnlyQuarantinedAuditBlocksCleanupWithoutRuntimeRows() { - String auditOnlyInstance = instanceId + "-AUDIT-ONLY"; - long quarantinedActorId = - insertActor( - "legacy audit destination", - UUID.randomUUID(), - null, - null, - null, - null, - "shared-live", - "QUARANTINED", - "OWNER_PROVENANCE_MISSING", - accountId, - tenantId); - 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 (" - + fixtureId(3601) - + ", ?, " - + fixtureId(3001) - + ", 1, 'TAKE', 'effect-audit-only-quarantined', 'corr-audit-only-quarantined', 'ROOM', ?, 'CHARACTER', ?, ?)", - tenantId, - auditOnlyInstance, - quarantinedActorId, - auditOnlyInstance); - - assertNoRuntimeRowsForInstance(auditOnlyInstance); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE id = ? AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", - Integer.class, - fixtureId(3601), - quarantinedActorId)) - .isEqualTo(1); - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - tenantId, auditOnlyInstance)) - .isTrue(); - assertThatThrownBy( - () -> - runtimeInstanceCleanupService.cleanupRuntimeInstance( - tenantId, 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 = ? AND tenant_id = ? AND correlation_key = 'corr-audit-only-quarantined' AND destination_character_id = ?", - Integer.class, - fixtureId(3601), - tenantId, - quarantinedActorId)) - .isEqualTo(1); - assertNoRuntimeRowsForInstance(auditOnlyInstance); - } - - @Test - void destinationOnlyOwnerResolvedAuditDoesNotBlockCleanupWithoutRuntimeRows() { - String auditOnlyInstance = instanceId + "-AUDIT-OWNER-RESOLVED"; - UUID ownerResolvedActorUuid = UUID.randomUUID(); - insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - long ownerResolvedActorId = - insertActor( - "owner-resolved audit destination fixture", - ownerResolvedActorUuid, - accountUuid, - tenantUuid, - namespaceUuid, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - accountId, - tenantId); - 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 (" - + fixtureId(3602) - + ", ?, " - + fixtureId(3001) - + ", 1, 'TAKE', 'effect-audit-only-owner-resolved', 'corr-audit-only-owner-resolved', 'ROOM', ?, 'CHARACTER', ?, ?)", - tenantId, - auditOnlyInstance, - ownerResolvedActorId, - auditOnlyInstance); - - assertNoRuntimeRowsForInstance(auditOnlyInstance); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE id = ? AND actor_character_id IS NULL AND source_character_id IS NULL AND destination_character_id = ?", - Integer.class, - fixtureId(3602), - ownerResolvedActorId)) - .isEqualTo(1); - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - tenantId, auditOnlyInstance)) - .isFalse(); - var result = - runtimeInstanceCleanupService.cleanupRuntimeInstance( - tenantId, 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 = ? AND tenant_id = ? AND correlation_key = 'corr-audit-only-owner-resolved' AND destination_character_id = ?", - Integer.class, - fixtureId(3602), - tenantId, - 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, - tenantId, - gameInstanceId)) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM container_instances WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - gameInstanceId)) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_stacks WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - gameInstanceId)) - .isZero(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT count(*) FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - gameInstanceId)) - .isZero(); - } - - @Test - void unresolvedRoomGroundIsHeldWithoutInferringActorOrS3Mapping() { - insertActor( - "legacy shared actor", - UUID.randomUUID(), - null, - null, - null, - null, - "shared-live", - "QUARANTINED", - "OWNER_PROVENANCE_MISSING", - accountId, - tenantId); - jdbcTemplate.update( - "INSERT INTO items (id, name, tenant_id, is_container) VALUES (" - + fixtureId(3901) - + ", 'Unresolved ground item', ?, false)", - tenantId); - jdbcTemplate.update( - "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) " - + "VALUES (?, ?, 'room-unresolved', " - + fixtureId(3901) - + ", 2, 1)", - tenantId, - instanceId); - - assertThat( - quarantinedActorRetentionRepository.hasUnclassifiedOrQuarantinedRuntimeEvidence( - tenantId, instanceId)) - .isTrue(); - assertThatThrownBy( - () -> - runtimeInstanceCleanupService.cleanupRuntimeInstance( - tenantId, instanceId, "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, - tenantId, - instanceId)) - .isEqualTo(2); - } - @Test void freshDefaultFlywayInstallsCompleteCombinedManifest() { // Flyway normalizes the declared Saga sub-location into its recursive parent location. @@ -835,9 +331,27 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getVersion().getVersion()) - .containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005"); + .containsExactly( + "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", + "1010"); + assertThat(flyway.info().applied()) + .filteredOn(migration -> migration.getVersion() != null) + .extracting(migration -> migration.getScript()) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql", + "V1003__quarantine_unresolved_actor_identity.sql", + "V1004__build_actor_identity_indexes_concurrently.sql", + "V1005__validate_actor_identity_constraints.sql", + "V1006__preseeded_actor_assignment.sql", + "V1007__preseeded_assignment_owner_snapshot.sql", + "V1008__canonical_gameplay_roster_snapshots.sql", + "V1009__canonical_publication_uuid_actor_evidence.sql", + "V1010__canonical_roster_owner_counters.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1005")); + .isEqualTo(MigrationVersion.fromVersion("1010")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -908,7 +422,9 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .containsExactlyElementsOf(parentHistory); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::version) - .containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005"); + .containsExactly( + "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", + "1010"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -918,7 +434,12 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "saga/V1002__saga_step_table.sql", "V1003__quarantine_unresolved_actor_identity.sql", "V1004__build_actor_identity_indexes_concurrently.sql", - "V1005__validate_actor_identity_constraints.sql"); + "V1005__validate_actor_identity_constraints.sql", + "V1006__preseeded_actor_assignment.sql", + "V1007__preseeded_assignment_owner_snapshot.sql", + "V1008__canonical_gameplay_roster_snapshots.sql", + "V1009__canonical_publication_uuid_actor_evidence.sql", + "V1010__canonical_roster_owner_counters.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1129,85 +650,6 @@ private void assertNamespaceIdentityUpdateRejected(String sql, Object... argumen .hasMessageContaining("entity playable-state namespace identity is immutable"); } - @Test - void characterUpdateRequiresExactTenantAndPreservesOwnerResolvedRowOnMismatch() { - UUID characterUuid = UUID.randomUUID(); - insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - long actorId = - insertActor( - "Tenant-owned actor", - characterUuid, - accountUuid, - tenantUuid, - namespaceUuid, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "shared-live", - "OWNER_RESOLVED", - null, - accountId, - tenantId); - - Character crossTenantUpdate = - characterRepository.findByIdAndTenantId(actorId, tenantId).orElseThrow(); - int originalVersion = crossTenantUpdate.getVersion(); - int originalExperience = crossTenantUpdate.getExperience(); - crossTenantUpdate.setTenantId(tenantId + 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, tenantId).orElseThrow(); - assertThat(unchanged.getTenantId()).isEqualTo(tenantId); - assertThat(unchanged.getName()).isEqualTo("Tenant-owned actor"); - assertThat(unchanged.getExperience()).isEqualTo(originalExperience); - assertThat(unchanged.getVersion()).isEqualTo(originalVersion); - - Character validUpdate = - characterRepository.findByIdAndTenantId(actorId, tenantId).orElseThrow(); - validUpdate.setName("Tenant-owned actor updated"); - Character saved = characterRepository.save(validUpdate); - assertThat(saved.getTenantId()).isEqualTo(tenantId); - assertThat(saved.getName()).isEqualTo("Tenant-owned actor updated"); - assertThat(saved.getVersion()).isEqualTo(originalVersion + 1); - } - - private Map inventoryHolderMutationCounts(long characterId) { - return Map.of( - "item_instances", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_instances WHERE tenant_id = ?", Integer.class, tenantId), - "container_instances", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM container_instances WHERE tenant_id = ?", - Integer.class, - tenantId), - "item_stacks", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_stacks WHERE tenant_id = ?", Integer.class, tenantId), - "inventory", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM inventory WHERE character_id = ?", Integer.class, characterId), - "room_ground_inventory", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM room_ground_inventory WHERE tenant_id = ? AND game_instance_id = ?", - Integer.class, - tenantId, - instanceId), - "item_transfer_audits", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM item_transfer_audits WHERE tenant_id = ?", - Integer.class, - tenantId), - "entity_mutation_effects", - jdbcTemplate.queryForObject( - "SELECT count(*) FROM entity_mutation_effects WHERE tenant_id = ?", - Integer.class, - tenantId)); - } - private long insertActor( String name, UUID characterUuid, @@ -1240,27 +682,6 @@ private long insertActor( 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, - tenantId, - characterId, - gameInstanceId, - containerId, - itemId, - "retained", - id, - visibleRef); - } - private void migrateLegacySchemaToParentFrontier() throws SQLException { testServiceSchema = "rai_" + UUID.randomUUID().toString().replace("-", ""); try (Connection connection = @@ -1281,7 +702,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1005")); + .isEqualTo(MigrationVersion.fromVersion("1010")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); 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/CanonicalGameplayRosterSelectedAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java new file mode 100644 index 0000000000..8390971388 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java @@ -0,0 +1,481 @@ +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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayRosterSelectedAssignmentServiceTest { + @Test + void resolvesCurrentTargetThenReturnsOnlyTheExactHistoricalAssignmentReference() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + CanonicalGameplayRosterOwnerEvidence evidence = + evidence(ownerRequest, request.expectedTarget()); + PreseededActorAssignmentExpectedTarget assignmentTarget = + assignmentTarget(request.expectedTarget()); + PreseededActorAssignmentReceipt receipt = receipt(request, assignmentTarget); + when(ownerPort.resolveCurrentTarget(ownerRequest)).thenReturn(evidence); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn(snapshot(request)); + when(repository.readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget, + request.expectedTarget().publishedOwnerProofDigest())) + .thenReturn(Optional.of(receipt)); + + CanonicalGameplayRosterSelectedAssignmentReference result = service.read(request); + + assertThat(result.requestUuid()).isEqualTo(request.requestUuid()); + assertThat(result.canonicalAccountUuid()).isEqualTo(request.canonicalAccountUuid()); + assertThat(result.selectedCharacterUuid()).isEqualTo(request.selectedCharacterUuid()); + assertThat(result.target()).isEqualTo(request.expectedTarget()); + assertThat(result.snapshot()).isEqualTo(request.expectedSnapshot()); + assertThat(result.assignmentUuid()).isEqualTo(receipt.assignmentUuid()); + assertThat(result.intentDigest()).isEqualTo(receipt.intentDigest()); + verify(ownerPort).resolveCurrentTarget(ownerRequest); + verify(repository) + .readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot()); + verify(repository) + .readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget, + request.expectedTarget().publishedOwnerProofDigest()); + } + + @Test + void ownerFailureAndRequestAccountOrTargetMismatchFailBeforeRepositoryRead() { + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + CanonicalGameplayRosterOwnerEvidencePort unavailableOwnerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository unavailableRepository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService unavailableService = + new CanonicalGameplayRosterSelectedAssignmentService( + unavailableOwnerPort, unavailableRepository); + + when(unavailableOwnerPort.resolveCurrentTarget(ownerRequest)) + .thenThrow( + new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException()); + assertThatThrownBy(() -> unavailableService.read(request)) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + verifyNoInteractions(unavailableRepository); + + assertOwnerMismatchBeforeRepository( + request, + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + UUID.randomUUID(), + request.expectedTarget(), + Instant.parse("2026-10-01T00:00:00Z")), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + new CanonicalGameplayRosterOwnerEvidence( + UUID.randomUUID(), + request.canonicalAccountUuid(), + request.expectedTarget(), + Instant.parse("2026-10-01T00:00:00Z")), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + evidence(ownerRequest, withNamespace(request.expectedTarget(), UUID.randomUUID())), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + evidence( + ownerRequest, + withScope(request.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)), + UnsupportedOperationException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_TARGET_UNSUPPORTED"); + assertOwnerMismatchBeforeRepository( + request, + evidence(ownerRequest, withCatalogRevision(request.expectedTarget(), 4L)), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + + @Test + void unsupportedCallerPolicyAndScopeFailBeforeOwnerResolution() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + + assertThatThrownBy( + () -> + service.read( + request( + withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + service.read( + request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)))) + .isInstanceOf(UnsupportedOperationException.class); + + verifyNoInteractions(ownerPort, repository); + } + + @Test + void ambientTransactionOrSynchronizationFailsBeforeOwnerAndRepositoryAccess() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(ownerPort, repository); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(ownerPort, repository); + } + + @Test + void missingOrInvalidStoredAssignmentFailsClosed() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + when(ownerPort.resolveCurrentTarget(ownerRequest)) + .thenReturn(evidence(ownerRequest, request.expectedTarget())); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn(snapshot(request)); + when(repository.readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget(request.expectedTarget()), + request.expectedTarget().publishedOwnerProofDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_UNAVAILABLE"); + } + + @Test + void changedSnapshotOrActorAbsentFromItFailsBeforeReceiptRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + when(ownerPort.resolveCurrentTarget(ownerRequest)) + .thenReturn(evidence(ownerRequest, request.expectedTarget())); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn( + new CanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), + request.expectedSnapshot().snapshotUuid(), + request.expectedSnapshot().snapshotDigest(), + request.expectedTarget(), + java.util.List.of(new CanonicalGameplayRosterActor(UUID.randomUUID(), "Other")))); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_NOT_IN_EXPECTED_SNAPSHOT"); + verify(repository, never()) + .readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget(request.expectedTarget()), + request.expectedTarget().publishedOwnerProofDigest()); + } + + private static CanonicalGameplayRosterSelectedAssignmentReadRequest request( + CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + UUID selectedUuid = UUID.randomUUID(); + return new CanonicalGameplayRosterSelectedAssignmentReadRequest( + requestUuid, + accountUuid, + selectedUuid, + target, + new CanonicalGameplayRosterSnapshotReference(UUID.randomUUID(), "a".repeat(64)), + executionContext(target, requestUuid, accountUuid, selectedUuid)); + } + + private static CanonicalGameplayRosterExecutionContext executionContext( + CanonicalGameplayRosterTarget target, + UUID requestUuid, + UUID accountUuid, + UUID characterUuid) { + return new CanonicalGameplayRosterExecutionContext( + accountUuid, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + characterUuid, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope()); + } + + private static CanonicalGameplayRosterSnapshot snapshot( + CanonicalGameplayRosterSelectedAssignmentReadRequest request) { + return new CanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), + request.expectedSnapshot().snapshotUuid(), + request.expectedSnapshot().snapshotDigest(), + request.expectedTarget(), + java.util.List.of( + new CanonicalGameplayRosterActor(request.selectedCharacterUuid(), "Selected Actor"))); + } + + private static void assertOwnerMismatchBeforeRepository( + CanonicalGameplayRosterSelectedAssignmentReadRequest request, + CanonicalGameplayRosterOwnerEvidence evidence, + Class expectedType, + String expectedMessage) { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + when(ownerPort.resolveCurrentTarget(ownerRequest)).thenReturn(evidence); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(expectedType) + .hasMessage(expectedMessage); + verifyNoInteractions(repository); + } + + private static CanonicalGameplayRosterOwnerEvidence evidence( + CanonicalGameplayRosterReadRequest request, CanonicalGameplayRosterTarget target) { + return new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + request.canonicalAccountUuid(), + target, + Instant.parse("2026-10-01T00:00:00Z")); + } + + private static CanonicalGameplayRosterTarget target() { + return new CanonicalGameplayRosterTarget( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID(), + 3L, + 17L, + 29L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "1".repeat(64), + "release/test", + "2".repeat(64), + "4".repeat(64), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + } + + private static PreseededActorAssignmentExpectedTarget assignmentTarget( + CanonicalGameplayRosterTarget target) { + return new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope()); + } + + private static PreseededActorAssignmentReceipt receipt( + CanonicalGameplayRosterSelectedAssignmentReadRequest request, + PreseededActorAssignmentExpectedTarget target) { + UUID assignmentUuid = UUID.randomUUID(); + PreseededActorCorePayload corePayload = + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Selected Actor"); + String intentDigest = + new PreseededActorAssignmentRequest( + assignmentUuid, request.canonicalAccountUuid(), corePayload, target) + .mutationIntentDigest(); + return new PreseededActorAssignmentReceipt( + assignmentUuid, + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + intentDigest, + target, + corePayload, + 1, + "dev", + 23L, + "ACCOUNT_DATABASE_INSERT", + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-01T00:00:00Z"), + 4L, + "5".repeat(64), + "6".repeat(64), + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + request.expectedTarget().publishedOwnerProofDigest(), + target.publishedReleaseBundleRef(), + "PRESEEDED_ONLY", + "ASSIGNED"); + } + + private static CanonicalGameplayRosterTarget withNamespace( + CanonicalGameplayRosterTarget target, UUID namespaceUuid) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + namespaceUuid, + target.playableStateScope(), + target.entryPolicy()); + } + + private static CanonicalGameplayRosterTarget withScope( + CanonicalGameplayRosterTarget target, PlayableStateScope scope) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + scope, + target.entryPolicy()); + } + + private static CanonicalGameplayRosterTarget withCatalogRevision( + CanonicalGameplayRosterTarget target, long catalogRevision) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + catalogRevision, + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.entryPolicy()); + } + + private static CanonicalGameplayRosterTarget withPolicy( + CanonicalGameplayRosterTarget target, CanonicalGameplayRosterEntryPolicy policy) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + policy); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java new file mode 100644 index 0000000000..1b5f2b3e43 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java @@ -0,0 +1,318 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayRosterServiceTest { + @Test + void exactOwnerResolvedPreseededTargetReadsPersistedSnapshot() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterOwnerEvidence evidence = evidence(request, request.expectedTarget()); + CanonicalGameplayRosterSnapshot expected = + new CanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), + UUID.randomUUID(), + "a".repeat(64), + request.expectedTarget(), + List.of(new CanonicalGameplayRosterActor(UUID.randomUUID(), "Persisted Actor"))); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence); + when(repository.captureCanonicalGameplayRosterSnapshot(request, evidence)).thenReturn(expected); + + assertThat(service.read(request)).isEqualTo(expected); + + verify(ownerPort).resolveCurrentTarget(request); + verify(repository).captureCanonicalGameplayRosterSnapshot(request, evidence); + } + + @Test + void unsupportedEntryPoliciesFailBeforeOwnerReadsOrRosterLookup() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + + assertThatThrownBy( + () -> + service.read( + request( + withPolicy(target(), CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED)))) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_ENTRY_POLICY_UNSUPPORTED"); + assertThatThrownBy( + () -> + service.read( + request( + withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + service.read( + request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.UNSPECIFIED)))) + .isInstanceOf(UnsupportedOperationException.class); + + verifyNoInteractions(ownerPort, repository); + } + + @Test + void independentlyResolvedCrossNamespaceTargetIsRejectedBeforeRepositoryRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterTarget differentNamespace = + new CanonicalGameplayRosterTarget( + request.expectedTarget().tenantUuid(), + request.expectedTarget().realmUuid(), + request.expectedTarget().worldSlug(), + request.expectedTarget().realmSlug(), + request.expectedTarget().gameInstanceUuid(), + request.expectedTarget().catalogRevision(), + request.expectedTarget().pointerVersion(), + request.expectedTarget().activeWorldEpoch(), + request.expectedTarget().canonicalVersionUuid(), + request.expectedTarget().publishedPolicyDigest(), + request.expectedTarget().publishedReleaseBundleRef(), + request.expectedTarget().admissionPointerSnapshotDigest(), + request.expectedTarget().publishedOwnerProofDigest(), + UUID.randomUUID(), + request.expectedTarget().playableStateScope(), + request.expectedTarget().entryPolicy()); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence(request, differentNamespace)); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + + verify(ownerPort).resolveCurrentTarget(request); + verifyNoInteractions(repository); + } + + @Test + void independentlyResolvedChangedOwnerCountersAreRejectedBeforeRepositoryRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterTarget changedPointer = + withCounters( + request.expectedTarget(), + request.expectedTarget().pointerVersion() + 1, + request.expectedTarget().activeWorldEpoch()); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence(request, changedPointer)); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + + verify(ownerPort).resolveCurrentTarget(request); + verifyNoInteractions(repository); + } + + @Test + void independentlyResolvedChangedActiveWorldEpochIsRejectedBeforeRepositoryRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterTarget changedEpoch = + withCounters( + request.expectedTarget(), + request.expectedTarget().pointerVersion(), + request.expectedTarget().activeWorldEpoch() + 1); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence(request, changedEpoch)); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + + verify(ownerPort).resolveCurrentTarget(request); + verifyNoInteractions(repository); + } + + @Test + void canonicalRosterDigestBindsPointerVersionAndActiveWorldEpoch() { + UUID accountUuid = UUID.randomUUID(); + CanonicalGameplayRosterTarget exactTarget = target(); + List actors = + List.of(new CanonicalGameplayRosterActor(UUID.randomUUID(), "Actor")); + + String exactDigest = + CanonicalGameplayRosterSnapshotDigest.compute(accountUuid, exactTarget, actors); + String changedPointerDigest = + CanonicalGameplayRosterSnapshotDigest.compute( + accountUuid, + withCounters( + exactTarget, exactTarget.pointerVersion() + 1, exactTarget.activeWorldEpoch()), + actors); + String changedEpochDigest = + CanonicalGameplayRosterSnapshotDigest.compute( + accountUuid, + withCounters( + exactTarget, exactTarget.pointerVersion(), exactTarget.activeWorldEpoch() + 1), + actors); + + assertThat(changedPointerDigest).isNotEqualTo(exactDigest); + assertThat(changedEpochDigest).isNotEqualTo(exactDigest); + assertThat(changedEpochDigest).isNotEqualTo(changedPointerDigest); + } + + @Test + void missingCurrentOwnerProducerFailsClosedWithoutRepositoryLookup() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + request -> { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + }; + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + + assertThatThrownBy(() -> service.read(request(target()))) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + + verifyNoInteractions(repository); + } + + @Test + void ownerReadCannotRunInsideAmbientTransactionOrSynchronization() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(ownerPort, repository); + } + + private static CanonicalGameplayRosterReadRequest request(CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + return new CanonicalGameplayRosterReadRequest( + requestUuid, + accountUuid, + target, + new CanonicalGameplayRosterExecutionContext( + accountUuid, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + null, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope())); + } + + private static CanonicalGameplayRosterOwnerEvidence evidence( + CanonicalGameplayRosterReadRequest request, CanonicalGameplayRosterTarget target) { + return new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + request.canonicalAccountUuid(), + target, + Instant.parse("2026-10-01T00:00:00Z")); + } + + private static CanonicalGameplayRosterTarget target() { + return new CanonicalGameplayRosterTarget( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID(), + 3L, + 17L, + 29L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "1".repeat(64), + "release/test", + "2".repeat(64), + "3".repeat(64), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + } + + private static CanonicalGameplayRosterTarget withPolicy( + CanonicalGameplayRosterTarget target, CanonicalGameplayRosterEntryPolicy policy) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + policy); + } + + private static CanonicalGameplayRosterTarget withCounters( + CanonicalGameplayRosterTarget target, long pointerVersion, long activeWorldEpoch) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + pointerVersion, + activeWorldEpoch, + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.entryPolicy()); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java new file mode 100644 index 0000000000..f20ed8774e --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java @@ -0,0 +1,682 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class PreseededActorAssignmentServiceTest { + private static final UUID ASSIGNMENT_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 TENANT_UUID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_UUID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID CHARACTER_UUID = + UUID.fromString("70000000-0000-4000-8000-000000000007"); + + @Test + void requiresDedicatedRunOwnedActionBeforeCallingAnyOwnerOrStorageBoundary() { + RunOwnedPreseededAssignmentAuthority runAuthority = + new RunOwnedPreseededAssignmentAuthority() { + @Override + public void requireAuthorized( + PreseededActorAssignmentRequest request, Action dedicatedAction) { + assertThat(dedicatedAction).isEqualTo(Action.PRESEEDED_ACTOR_ASSIGNMENT); + assertThat(request.corePayload().actorKind()) + .isEqualTo(PreseededActorCorePayload.ActorKind.PLAYER); + throw new IllegalStateException("fixture capability did not grant this action"); + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence exactTarget, + Action dedicatedAction) { + throw new AssertionError("target grant check must follow initial action grant"); + } + }; + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not grant this action"); + + verifyNoInteractions(accountClient, ownerPort, characterRepository); + } + + @Test + void bindsDedicatedGrantToExactCurrentTargetAndCorePayloadBeforePersistingActor() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentRequest request = request(); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence target = ownerEvidence(); + PreseededActorAssignmentResult persisted = + new PreseededActorAssignmentResult( + ASSIGNMENT_UUID, + PreseededActorAssignmentResult.Outcome.ASSIGNED, + CHARACTER_UUID, + "a".repeat(64)); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(target); + when(characterRepository.assignPreseededActor( + eq(request), eq(target), eq(accountProof), any(String.class))) + .thenReturn(persisted); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThat(service.assign(request())).isEqualTo(persisted); + + verify(runAuthority) + .requireAuthorized( + request, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(accountClient) + .resolveRuntimeAccountIdentity(ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString()); + verify(ownerPort).resolveCurrentEligibleTarget(request, accountProof, stagingEvidence()); + verify(runAuthority) + .requireTargetBoundAuthorized( + request, + target, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(characterRepository) + .assignPreseededActor(eq(request), eq(target), eq(accountProof), any(String.class)); + } + + @Test + void changedGrantTargetOrPayloadIsRejectedBeforeRepositoryReplay() { + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentOwnerEvidence target = ownerEvidence(); + RunOwnedPreseededAssignmentAuthority runAuthority = + new RunOwnedPreseededAssignmentAuthority() { + @Override + public void requireAuthorized( + PreseededActorAssignmentRequest authorizedRequest, Action dedicatedAction) { + assertThat(authorizedRequest).isEqualTo(request); + assertThat(dedicatedAction).isEqualTo(Action.PRESEEDED_ACTOR_ASSIGNMENT); + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest authorizedRequest, + PreseededActorAssignmentOwnerEvidence currentTarget, + Action dedicatedAction) { + assertThat(authorizedRequest).isEqualTo(request); + assertThat(currentTarget).isEqualTo(target); + assertThat(dedicatedAction).isEqualTo(Action.PRESEEDED_ACTOR_ASSIGNMENT); + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_GRANT_INTENT_MISMATCH"); + } + }; + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(target); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_GRANT_INTENT_MISMATCH"); + + verifyNoInteractions(characterRepository); + } + + @Test + void rejectsUnknownAccountProofBeforeReadingAssignmentTarget() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn( + new RuntimeAccountIdentityEvidence( + 1, + "dev", + UUID.fromString("80000000-0000-4000-8000-000000000008"), + ACCOUNT_UUID, + 23L, + "ACCOUNT_DATABASE_INSERT")); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_PROOF_MISMATCH"); + + verify(ownerPort, never()).resolveCurrentEligibleTarget(any(), any(), any()); + verifyNoInteractions(characterRepository); + } + + @Test + void deniesIneligibleAccountSnapshotBeforeGameSessionOwnerReadOrAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorStagingEligibilityPort stagingPort = + mock(PreseededActorStagingEligibilityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof()); + when(stagingPort.resolvePreseededActorStagingEligibility( + ACCOUNT_UUID.toString(), TENANT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(stagingEvidence(false)); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort, ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + + verifyNoInteractions(ownerPort, characterRepository); + } + + @Test + void rejectsOwnerEvidenceNotBoundToTheExactAccountStagingSnapshot() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentOwnerEvidence mismatchedTarget = + ownerEvidenceWithAccountSnapshotDigest("5".repeat(64)); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(mismatchedTarget); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_MISMATCH"); + + verify(runAuthority, never()).requireTargetBoundAuthorized(any(), any(), any()); + verifyNoInteractions(characterRepository); + } + + @Test + void deniesIneligibleOwnerEvidenceBeforeTargetGrantOrRepositoryAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence ineligible = + new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.INELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 9L, + "1".repeat(64), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "3".repeat(64), + "4".repeat(64), + "release-bundle/test"); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenReturn(ineligible); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + + verify(runAuthority, never()).requireTargetBoundAuthorized(any(), any(), any()); + verify(characterRepository, never()).assignPreseededActor(any(), any(), any(), any()); + } + + @Test + void deniesAbsentOwnerProofBeforeRepositoryAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenReturn(null); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_PROOF_MISMATCH"); + + verify(characterRepository, never()).assignPreseededActor(any(), any(), any(), any()); + } + + @Test + void deniesUnavailableOwnerEvidenceBeforeRepositoryAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenThrow(new IllegalStateException("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE")); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE"); + + verifyNoInteractions(characterRepository); + } + + @Test + void rejectsEveryChangedExpectedTargetFieldBeforeRepositoryReplay() { + for (int changedField = 0; changedField < 11; changedField++) { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = + mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence changedTarget = changedTarget(changedField); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenReturn(changedTarget); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .as("changed expected target field index %s", changedField) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + + verify(runAuthority, never()).requireTargetBoundAuthorized(any(), any(), any()); + verifyNoInteractions(characterRepository); + } + } + + @Test + void exactReplayReturnsStoredActorOnlyAfterGrantAndOwnerChecksForCompleteTuple() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentRequest exactRequest = request(); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence exactTarget = ownerEvidence(); + PreseededActorAssignmentResult storedReplay = + new PreseededActorAssignmentResult( + ASSIGNMENT_UUID, + PreseededActorAssignmentResult.Outcome.ASSIGNED, + CHARACTER_UUID, + "a".repeat(64)); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(exactRequest, accountProof, stagingEvidence())) + .thenReturn(exactTarget); + when(characterRepository.assignPreseededActor( + eq(exactRequest), eq(exactTarget), eq(accountProof), any(String.class))) + .thenReturn(storedReplay); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThat(service.assign(exactRequest)).isEqualTo(storedReplay); + assertThat(service.assign(exactRequest)).isEqualTo(storedReplay); + + verify(runAuthority, times(2)) + .requireAuthorized( + exactRequest, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(runAuthority, times(2)) + .requireTargetBoundAuthorized( + exactRequest, + exactTarget, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(characterRepository, times(2)) + .assignPreseededActor( + eq(exactRequest), eq(exactTarget), eq(accountProof), any(String.class)); + } + + @Test + void intentDigestBindsFullTargetAndPayloadButIgnoresEligibilityRefreshEvidence() { + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentOwnerEvidence baseline = ownerEvidence(); + PreseededActorAssignmentOwnerEvidence reevaluated = + new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + Instant.parse("2026-10-04T00:05:00Z"), + 10L, + "4".repeat(64), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + "game-instance", + baseline.catalogRevision(), + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + PreseededActorAssignmentOwnerEvidence changedCatalog = + new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + "game-instance", + baseline.catalogRevision() + 1, + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + PreseededActorAssignmentOwnerEvidence changedScope = + new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + "game-instance", + baseline.catalogRevision(), + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + PreseededActorAssignmentRequest changedPayload = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Changed Actor"), + request.expectedTarget()); + PreseededActorAssignmentRequest changedAccount = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + UUID.fromString("80000000-0000-4000-8000-000000000008"), + request.corePayload(), + request.expectedTarget()); + + String digest = PreseededActorAssignmentIntentDigest.compute(request, baseline); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, reevaluated)) + .isEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedCatalog)) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedScope)) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedTarget(4))) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedTarget(10))) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(changedPayload, baseline)) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(changedAccount, baseline)) + .isNotEqualTo(digest); + } + + private static PreseededActorAssignmentRequest request() { + return new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Assigned Actor"), + expectedTarget()); + } + + private static PreseededActorAssignmentExpectedTarget expectedTarget() { + return new PreseededActorAssignmentExpectedTarget( + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + private static PreseededActorAssignmentOwnerEvidence changedTarget(int field) { + PreseededActorAssignmentOwnerEvidence baseline = ownerEvidence(); + return new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + field == 0 + ? UUID.fromString("80000000-0000-4000-8000-000000000008") + : baseline.canonicalTenantUuid(), + field == 1 ? UUID.fromString("90000000-0000-4000-8000-000000000009") : baseline.realmUuid(), + field == 2 ? "other-world" : baseline.worldSlug(), + field == 3 ? "other-realm" : baseline.realmSlug(), + field == 4 ? "other-game-instance" : baseline.gameInstanceId(), + field == 5 ? baseline.catalogRevision() + 1 : baseline.catalogRevision(), + field == 6 + ? UUID.fromString("18000000-0000-4000-8000-000000000018") + : baseline.canonicalVersionUuid(), + field == 7 ? "3".repeat(64) : baseline.frozenPolicyDigest(), + field == 8 + ? UUID.fromString("a0000000-0000-4000-8000-00000000000a") + : baseline.playableStateNamespaceId(), + field == 10 + ? PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + : baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + field == 9 ? "release-bundle/changed" : baseline.publishedReleaseBundleRef()); + } + + private static PreseededActorStagingEligibilityPort stagingPort() { + return (accountUuid, tenantUuid, assignmentUuid) -> { + assertThat(accountUuid).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(tenantUuid).isEqualTo(TENANT_UUID.toString()); + assertThat(assignmentUuid).isEqualTo(ASSIGNMENT_UUID.toString()); + return stagingEvidence(); + }; + } + + private static AccountActorStagingEligibilityEvidence stagingEvidence() { + return stagingEvidence(true); + } + + private static AccountActorStagingEligibilityEvidence stagingEvidence(boolean eligible) { + return AccountActorStagingEligibilityEvidence.seal( + "dev", + ASSIGNMENT_UUID, + ACCOUNT_UUID, + TENANT_UUID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-04T00:00:00Z"), + "ACCOUNT_DATABASE_INSERT", + eligible ? "ACTIVE" : "DEACTIVATED_PENDING_DELETE", + eligible ? "ACTIVE" : "INACTIVE", + eligible, + "EXPLICIT_JOIN", + 17L, + 9L, + "FRESH_GAME_DESIGN", + UUID.fromString("60000000-0000-4000-8000-000000000006"), + "sha256:" + "a".repeat(64), + 23L, + UUID.fromString("70000000-0000-4000-8000-000000000007"), + "sha256:" + "b".repeat(64), + false); + } + + private static RuntimeAccountIdentityEvidence accountProof() { + return new RuntimeAccountIdentityEvidence( + 1, "dev", ASSIGNMENT_UUID, ACCOUNT_UUID, 23L, "ACCOUNT_DATABASE_INSERT"); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { + return new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + stagingEvidence().observedAt(), + stagingEvidence().membershipAuthorityGeneration(), + stagingEvidence().eligibilityDecisionDigest(), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + stagingEvidence().authoritySnapshotDigest(), + "4".repeat(64), + "release-bundle/test"); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidenceWithAccountSnapshotDigest( + String accountSnapshotDigest) { + PreseededActorAssignmentOwnerEvidence baseline = ownerEvidence(); + return new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + baseline.gameInstanceId(), + baseline.catalogRevision(), + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + accountSnapshotDigest, + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java new file mode 100644 index 0000000000..e9145597ea --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class PreseededActorCorePayloadTest { + @Test + void rejectsMissingBlankOverlongOrControlCharacterDisplayNames() { + assertThatThrownBy( + () -> new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, " ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "x".repeat(101))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\nName")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnpairedUtf16Surrogates() { + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uD800Name")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uDC00Name")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsAWellFormedAstralNameAtTheCodePointLimit() { + String displayName = "\uD83D\uDE00" + "x".repeat(99); + + PreseededActorCorePayload payload = + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, displayName); + + org.assertj.core.api.Assertions.assertThat(payload.displayName()).isEqualTo(displayName); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java new file mode 100644 index 0000000000..0edcc33177 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java @@ -0,0 +1,428 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.time.Instant; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class RunOwnedPreseededActorAssignmentAuthorityAdapterTest { + private static final String RUN_ID = "compose-smoke-9123"; + private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-9123"; + private static final String NAMESPACE = "dev"; + private static final String URI = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String TRUST_ROOT_SHA256 = "b".repeat(64); + private static final UUID ASSIGNMENT_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 TENANT_UUID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_UUID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + + @BeforeEach + void clearSessionContextBeforeTest() { + SessionContext.clear(); + } + + @AfterEach + void clearSessionContextAfterTest() { + SessionContext.clear(); + } + + @Test + void validatesExactGrantThenRechecksItAgainstIndependentOwnerTarget(@TempDir Path directory) + throws Exception { + Path capabilityFile = writeGrant(directory, request()); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + + withGameSessionPeer( + () -> { + assertThatCode( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidence(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidenceWithNamespace( + UUID.fromString("60000000-0000-4000-8000-000000000006")), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + }); + } + + @Test + void changedOrAbsentGrantDeniesBeforeOwnerReadsAndRepositoryMutation(@TempDir Path directory) + throws Exception { + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentRequest otherIntent = + new PreseededActorAssignmentRequest( + UUID.fromString("10000000-0000-4000-8000-000000000009"), + ACCOUNT_UUID, + request.corePayload(), + request.expectedTarget()); + Path capabilityFile = writeGrant(directory, otherIntent); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + PreseededActorAccountIdentityPort accountIdentityPort = + mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + authority, accountIdentityPort, stagingPort(), ownerEvidencePort, characterRepository); + + withGameSessionPeer( + () -> + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class)); + verifyNoInteractions(accountIdentityPort, ownerEvidencePort, characterRepository); + + RunOwnedPreseededActorAssignmentAuthorityAdapter missingCapability = authority(""); + withGameSessionPeer( + () -> + assertThatThrownBy( + () -> + missingCapability.requireAuthorized( + request, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); + } + + @Test + void authenticatedUriMustBeExactAndUserContextRemainsDenied(@TempDir Path directory) + throws Exception { + Path capabilityFile = writeGrant(directory, request()); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + + assertThatThrownBy( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")) + .run( + () -> + assertThatThrownBy( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action + .PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); + + SessionContext.setContext(ACCOUNT_UUID.toString(), List.of(), java.util.Map.of()); + try { + withGameSessionPeer( + () -> + assertThatThrownBy( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action + .PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); + } finally { + SessionContext.clear(); + } + } + + @Test + void grantReplacementBetweenOwnerReadsAndPersistenceFailsClosed(@TempDir Path directory) + throws Exception { + PreseededActorAssignmentRequest request = request(); + Path capabilityFile = writeGrant(directory, request); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + RuntimeAccountIdentityEvidence accountProof = + new RuntimeAccountIdentityEvidence( + 1, "dev", ASSIGNMENT_UUID, ACCOUNT_UUID, 23L, "ACCOUNT_DATABASE_INSERT"); + PreseededActorAccountIdentityPort accountIdentityPort = + mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + authority, accountIdentityPort, stagingPort(), ownerEvidencePort, characterRepository); + when(accountIdentityPort.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenAnswer( + invocation -> { + PreseededActorAssignmentRequest replacement = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Changed Actor"), + request.expectedTarget()); + replaceGrant(capabilityFile, replacement); + return accountProof; + }); + when(ownerEvidencePort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(ownerEvidence()); + + withGameSessionPeer( + () -> + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class)); + + verifyNoInteractions(characterRepository); + } + + @Test + void activeServerTrustRootPinIsReevaluatedAtTheOwnerBoundBoundary(@TempDir Path directory) + throws Exception { + Path capabilityFile = writeGrant(directory, request()); + AtomicReference activeTrustRoot = new AtomicReference<>(TRUST_ROOT_SHA256); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + new RunOwnedPreseededActorAssignmentAuthorityAdapter( + capabilityFile.toString(), RUN_ID, PROJECT_NAME, NAMESPACE, activeTrustRoot::get); + + withGameSessionPeer( + () -> { + authority.requireAuthorized( + request(), RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + activeTrustRoot.set("c".repeat(64)); + assertThatThrownBy( + () -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidence(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + }); + } + + private static RunOwnedPreseededActorAssignmentAuthorityAdapter authority(String path) { + return new RunOwnedPreseededActorAssignmentAuthorityAdapter( + path, RUN_ID, PROJECT_NAME, NAMESPACE, () -> TRUST_ROOT_SHA256); + } + + private static void withGameSessionPeer(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity(URI, NAMESPACE, "game-session-service")) + .run(action); + } + + private static Path writeGrant(Path directory, PreseededActorAssignmentRequest request) + throws Exception { + Files.setPosixFilePermissions( + directory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE)); + Path file = directory.resolve("run-owned-assignment-grant.json"); + Files.writeString(file, capabilityJson(request), StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + file, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + return file; + } + + private static void replaceGrant(Path file, PreseededActorAssignmentRequest request) + throws Exception { + Files.setPosixFilePermissions( + file, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + Files.writeString(file, capabilityJson(request), StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + file, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + } + + private static String capabilityJson(PreseededActorAssignmentRequest request) { + PreseededActorAssignmentExpectedTarget target = request.expectedTarget(); + return String.join( + "%n", + "{", + " \"schema\": \"%s\",", + " \"runId\": \"%s\",", + " \"composeProjectName\": \"%s\",", + " \"action\": \"%s\",", + " \"trustedGameSessionUriSan\": \"%s\",", + " \"trustedGameSessionNamespace\": \"%s\",", + " \"assignmentUuid\": \"%s\",", + " \"canonicalAccountUuid\": \"%s\",", + " \"expectedTarget\": {", + " \"canonicalTenantUuid\": \"%s\",", + " \"realmUuid\": \"%s\",", + " \"worldSlug\": \"%s\",", + " \"realmSlug\": \"%s\",", + " \"gameInstanceId\": \"%s\",", + " \"catalogRevision\": %d,", + " \"canonicalVersionUuid\": \"%s\",", + " \"frozenPolicyDigest\": \"%s\",", + " \"playableStateNamespaceUuid\": \"%s\",", + " \"publishedReleaseBundleRef\": \"%s\",", + " \"playableStateScope\": \"%s\"", + " },", + " \"corePayload\": {", + " \"actorKind\": \"%s\",", + " \"displayName\": \"%s\"", + " },", + " \"intentDigest\": \"%s\",", + " \"entityServerTrustRootSha256\": \"%s\"", + "}") + .formatted( + RunOwnedPreseededActorAssignmentCapability.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + RunOwnedPreseededActorAssignmentCapability.ACTION, + URI, + NAMESPACE, + request.assignmentUuid(), + request.canonicalAccountUuid(), + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope().name(), + request.corePayload().actorKind().name(), + request.corePayload().displayName(), + PreseededActorAssignmentGrantIntentDigest.compute(request), + TRUST_ROOT_SHA256); + } + + private static PreseededActorStagingEligibilityPort stagingPort() { + return (accountUuid, tenantUuid, assignmentUuid) -> { + if (!ACCOUNT_UUID.toString().equals(accountUuid) + || !TENANT_UUID.toString().equals(tenantUuid) + || !ASSIGNMENT_UUID.toString().equals(assignmentUuid)) { + throw new IllegalStateException("unexpected Account staging evidence request"); + } + return stagingEvidence(); + }; + } + + private static AccountActorStagingEligibilityEvidence stagingEvidence() { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + ASSIGNMENT_UUID, + ACCOUNT_UUID, + TENANT_UUID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-04T00:00:00Z"), + "ACCOUNT_DATABASE_INSERT", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 17L, + 9L, + "FRESH_GAME_DESIGN", + UUID.fromString("60000000-0000-4000-8000-000000000006"), + "sha256:" + "a".repeat(64), + 23L, + UUID.fromString("70000000-0000-4000-8000-000000000007"), + "sha256:" + "b".repeat(64), + false); + } + + private static PreseededActorAssignmentRequest request() { + return new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Assigned Actor"), + new PreseededActorAssignmentExpectedTarget( + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { + return ownerEvidenceWithNamespace(NAMESPACE_UUID); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidenceWithNamespace( + UUID namespaceUuid) { + return new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + stagingEvidence().observedAt(), + stagingEvidence().membershipAuthorityGeneration(), + stagingEvidence().eligibilityDecisionDigest(), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + stagingEvidence().authoritySnapshotDigest(), + "4".repeat(64), + "release-bundle/test"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java new file mode 100644 index 0000000000..7e5b8f569c --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java @@ -0,0 +1,353 @@ +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.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.cert.CertificateExpiredException; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class RunOwnedPreseededActorAssignmentCapabilityTest { + private static final String RUN_ID = "compose-smoke-9123"; + private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-9123"; + private static final String NAMESPACE = "dev"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String ENTITY_TRUST_ROOT_SHA256 = "b".repeat(64); + private static final UUID ASSIGNMENT_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 TENANT_UUID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_UUID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + + @Test + void parsesExactGrantAndBindsRunProjectPeerAssignmentTargetPayloadAndTlsTrustRoot() { + RunOwnedPreseededActorAssignmentCapability capability = parse(validJson()); + + assertThat(capability.matchesRequest(request())).isTrue(); + assertThat(capability.matchesOwnerTarget(request(), ownerEvidence())).isTrue(); + } + + @Test + void rejectsUnknownDuplicateAndChangedIntentFields() { + assertInvalid( + validJson() + .replace( + RunOwnedPreseededActorAssignmentCapability.CAPABILITY_SCHEMA, + "firemud.run-owned-preseeded-actor-assignment.v2")); + assertInvalid( + validJson() + .replace( + "\"canonicalVersionUuid\": \"" + + request().expectedTarget().canonicalVersionUuid() + + "\"", + "\"publishedVersionId\": 17, \"publishedVersionNumber\": 2")); + assertInvalid(validJson().replace("\"action\":", "\"unexpected\":true,\"action\":")); + assertInvalid( + validJson() + .replace( + "\"action\": \"PRESEEDED_ACTOR_ASSIGNMENT\"", + "\"action\": \"PRESEEDED_ACTOR_ASSIGNMENT\"," + + "\"action\": \"PRESEEDED_ACTOR_ASSIGNMENT\"")); + assertInvalid( + validJson().replace("\"worldSlug\": \"world\"", "\"extra\": 1, \"worldSlug\": \"world\"")); + assertInvalid( + validJson() + .replace("\"actorKind\": \"PLAYER\"", "\"extra\": 1, \"actorKind\": \"PLAYER\"")); + assertInvalid( + validJson() + .replace( + "\"assignmentUuid\": \"" + ASSIGNMENT_UUID, + "\"assignmentUuid\": \"10000000-0000-4000-8000-000000000009")); + assertInvalid( + validJson() + .replace("\"displayName\": \"Assigned Actor\"", "\"displayName\": \"Changed Actor\"")); + assertInvalid(validJson().replace(ENTITY_TRUST_ROOT_SHA256, "c".repeat(64))); + } + + @Test + void rejectsChangedConfiguredRunProjectPeerNamespaceAndTrustRoot() { + byte[] json = validJson().getBytes(StandardCharsets.UTF_8); + + assertInvalid( + json, "different-run", PROJECT_NAME, GAME_SESSION_URI, NAMESPACE, ENTITY_TRUST_ROOT_SHA256); + assertInvalid( + json, RUN_ID, "different-project", GAME_SESSION_URI, NAMESPACE, ENTITY_TRUST_ROOT_SHA256); + assertInvalid( + json, + RUN_ID, + PROJECT_NAME, + "spiffe://firemud/ns/other/sa/game-session-service", + NAMESPACE, + ENTITY_TRUST_ROOT_SHA256); + assertInvalid(json, RUN_ID, PROJECT_NAME, GAME_SESSION_URI, "other", ENTITY_TRUST_ROOT_SHA256); + assertInvalid(json, RUN_ID, PROJECT_NAME, GAME_SESSION_URI, NAMESPACE, "d".repeat(64)); + } + + @Test + void rejectsWritableSymlinkedAndOversizedCapabilityFiles(@TempDir Path directory) + throws Exception { + makePrivateDirectory(directory); + Path writableCapability = writeCapability(directory.resolve("writable.json")); + assertThatThrownBy( + () -> RunOwnedPreseededActorAssignmentCapability.readCapability(writableCapability)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + Path readonlyCapability = writeCapability(directory.resolve("readonly.json")); + Files.setPosixFilePermissions(readonlyCapability, readOnlyFilePermissions()); + Path symlink = directory.resolve("symlink.json"); + Files.createSymbolicLink(symlink, readonlyCapability.getFileName()); + assertThatThrownBy(() -> RunOwnedPreseededActorAssignmentCapability.readCapability(symlink)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + Path oversized = directory.resolve("oversized.json"); + Files.writeString(oversized, "x".repeat(16 * 1024 + 1)); + Files.setPosixFilePermissions(oversized, readOnlyFilePermissions()); + assertThatThrownBy(() -> RunOwnedPreseededActorAssignmentCapability.readCapability(oversized)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + } + + @Test + void readsOnlyOwnerBoundNonWritableCapabilityFile(@TempDir Path directory) throws Exception { + makePrivateDirectory(directory); + Path capabilityFile = writeCapability(directory.resolve("capability.json")); + Files.setPosixFilePermissions(capabilityFile, readOnlyFilePermissions()); + + assertThat(RunOwnedPreseededActorAssignmentCapability.readCapability(capabilityFile)) + .isEqualTo(validJson().getBytes(StandardCharsets.UTF_8)); + } + + @Test + void trustRootPinRequiresOneValidCaAndUsesExactLoadedCertificateFingerprint() throws Exception { + X509Certificate trustedRoot = mock(X509Certificate.class); + when(trustedRoot.getBasicConstraints()).thenReturn(1); + when(trustedRoot.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + + assertThat( + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot))) + .isEqualTo( + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(new byte[] {1, 2, 3}))); + + String configuredFingerprint = + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot)); + X509TrustManager loadedTrustManager = mock(X509TrustManager.class); + when(loadedTrustManager.getAcceptedIssuers()).thenReturn(new X509Certificate[] {trustedRoot}); + assertThat( + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, configuredFingerprint)) + .isEqualTo(configuredFingerprint); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, "c".repeat(64))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + when(loadedTrustManager.getAcceptedIssuers()) + .thenReturn(new X509Certificate[] {trustedRoot, trustedRoot}); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, configuredFingerprint)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + doThrow(new CertificateExpiredException()).when(trustedRoot).checkValidity(); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot, trustedRoot))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + } + + private static RunOwnedPreseededActorAssignmentCapability parse(String json) { + return parse( + json.getBytes(StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + GAME_SESSION_URI, + NAMESPACE, + ENTITY_TRUST_ROOT_SHA256); + } + + private static RunOwnedPreseededActorAssignmentCapability parse( + byte[] json, + String runId, + String projectName, + String gameSessionUri, + String namespace, + String trustRootSha256) { + return RunOwnedPreseededActorAssignmentCapability.parseAndValidate( + json, runId, projectName, gameSessionUri, namespace, trustRootSha256); + } + + private static void assertInvalid(String json) { + assertInvalid( + json.getBytes(StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + GAME_SESSION_URI, + NAMESPACE, + ENTITY_TRUST_ROOT_SHA256); + } + + private static void assertInvalid( + byte[] json, + String runId, + String projectName, + String gameSessionUri, + String namespace, + String trustRootSha256) { + assertThatThrownBy( + () -> parse(json, runId, projectName, gameSessionUri, namespace, trustRootSha256)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + } + + private static Path writeCapability(Path path) throws Exception { + return Files.writeString(path, validJson()); + } + + private static void makePrivateDirectory(Path directory) throws Exception { + Files.setPosixFilePermissions( + directory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE)); + } + + private static Set readOnlyFilePermissions() { + return Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + } + + private static PreseededActorAssignmentRequest request() { + return new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Assigned Actor"), + new PreseededActorAssignmentExpectedTarget( + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { + return new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 9L, + "1".repeat(64), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "3".repeat(64), + "4".repeat(64), + "release-bundle/test"); + } + + private static String validJson() { + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentExpectedTarget target = request.expectedTarget(); + return String.join( + "%n", + "{", + " \"schema\": \"%s\",", + " \"runId\": \"%s\",", + " \"composeProjectName\": \"%s\",", + " \"action\": \"%s\",", + " \"trustedGameSessionUriSan\": \"%s\",", + " \"trustedGameSessionNamespace\": \"%s\",", + " \"assignmentUuid\": \"%s\",", + " \"canonicalAccountUuid\": \"%s\",", + " \"expectedTarget\": {", + " \"canonicalTenantUuid\": \"%s\",", + " \"realmUuid\": \"%s\",", + " \"worldSlug\": \"%s\",", + " \"realmSlug\": \"%s\",", + " \"gameInstanceId\": \"%s\",", + " \"catalogRevision\": %d,", + " \"canonicalVersionUuid\": \"%s\",", + " \"frozenPolicyDigest\": \"%s\",", + " \"playableStateNamespaceUuid\": \"%s\",", + " \"publishedReleaseBundleRef\": \"%s\",", + " \"playableStateScope\": \"%s\"", + " },", + " \"corePayload\": {", + " \"actorKind\": \"%s\",", + " \"displayName\": \"%s\"", + " },", + " \"intentDigest\": \"%s\",", + " \"entityServerTrustRootSha256\": \"%s\"", + "}") + .formatted( + RunOwnedPreseededActorAssignmentCapability.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + RunOwnedPreseededActorAssignmentCapability.ACTION, + GAME_SESSION_URI, + NAMESPACE, + request.assignmentUuid(), + request.canonicalAccountUuid(), + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope().name(), + request.corePayload().actorKind().name(), + request.corePayload().displayName(), + PreseededActorAssignmentGrantIntentDigest.compute(request), + ENTITY_TRUST_ROOT_SHA256); + } +} 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 3ecafd1c27..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.firedevops.firemud.entitymanagement.service; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import 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)); - - 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"); - verifyNoInteractions(repository); - } -} 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/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index c93665f599..8bf1256098 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -39,7 +39,6 @@ import net.firedevops.firemud.entitymanagement.service.InventoryService; import net.firedevops.firemud.entitymanagement.service.PingService; import net.firedevops.firemud.entitymanagement.service.RoomEntityService; -import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; import net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionRequest; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionResponse; @@ -1720,83 +1719,6 @@ public void onCompleted() {} verifyNoInteractions(runtimeInstanceCleanupService); } - @Test - void cleanupRuntimeInstanceReturnsFailedPreconditionForKnownCleanupHold() { - RuntimeInstanceCleanupService cleanupService = - Mockito.mock(RuntimeInstanceCleanupService.class); - String holdMessage = "ENTITY_UNCLASSIFIED_OR_QUARANTINED_EVIDENCE_BLOCKS_CLEANUP: held"; - Mockito.when(cleanupService.cleanupRuntimeInstance(1L, "GI-1", "term-1")) - .thenThrow(new RuntimeInstanceCleanupHeldException(holdMessage)); - - var response = invokeCleanupRuntimeInstance(cleanupService); - - assertEquals("FAILED_PRECONDITION", response.getError().getCode()); - assertEquals(holdMessage, response.getError().getMessage()); - } - - @Test - void cleanupRuntimeInstanceKeepsUnexpectedFailuresInternal() { - RuntimeInstanceCleanupService cleanupService = - Mockito.mock(RuntimeInstanceCleanupService.class); - Mockito.when(cleanupService.cleanupRuntimeInstance(1L, "GI-1", "term-1")) - .thenThrow(new IllegalStateException("unexpected")); - - var response = invokeCleanupRuntimeInstance(cleanupService); - - assertEquals("INTERNAL", response.getError().getCode()); - } - - private net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse - invokeCleanupRuntimeInstance(RuntimeInstanceCleanupService cleanupService) { - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); - try { - EntityManagementGrpcService service = - new EntityManagementGrpcService( - Mockito.mock(PingService.class), - Mockito.mock(CharacterService.class), - Mockito.mock(ActorStateService.class), - Mockito.mock(ActorConditionMutationService.class), - Mockito.mock(EntityDraftDesignDigestService.class), - Mockito.mock(EquipmentService.class), - Mockito.mock(InventoryService.class), - Mockito.mock(ContainerService.class), - Mockito.mock(RoomEntityService.class), - cleanupService, - effectReplayService(), - Mockito.mock(EntityUpgradeValidationService.class), - Mockito.mock(EntityTemplateReferenceService.class), - attestationService(), - new SimpleMeterRegistry(), - new EffectPayloadParser(new ObjectMapper()), - TEST_NAMESPACE); - AtomicReference - ref = new AtomicReference<>(); - service.cleanupRuntimeInstance( - net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceRequest.newBuilder() - .setTenantId("1") - .setGameInstanceId("GI-1") - .setTerminationRequestId("term-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - return ref.get(); - } finally { - SessionContext.clear(); - } - } - @Test void autowiredConstructorDelegatesCleanupToInjectedRuntimeService() { RuntimeInstanceCleanupService runtimeInstanceCleanupService = 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 1cc27334b6..0000000000 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.java +++ /dev/null @@ -1,59 +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 net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupHeldException; -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(RuntimeInstanceCleanupHeldException.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 c19b9d626cae97902e0625b4be9212712f7c5cc5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:18:39 +1300 Subject: [PATCH 07/28] Supply required receipt mount placeholder during bootstrap configuration discovery --- design/project-management/ai-observations.md | 5 +++++ dev-tools/verify-fresh-bootstrap.sh | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 240a291443..b2a97090c2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -235,3 +235,8 @@ Entry format: - Observation: the wrong class filter executed no tests and failed explicitly; the static tasks were reported `SKIPPED` despite a successful focused unit build. Neither result qualified the missing proof. - Expected pattern: read the class’s declared package before specifying a test filter, and verify task execution rather than equating build success with every requested check passing. Enable the repository’s canonical full-check property when selecting static tasks. - Current status: corrected package selection passed 50 focused unit cases; the subsequent runtime fix passed 58 selected unit cases. A separate canonical `-PfullCheck` run executed the required static checks successfully. No validation requirement was waived. + +- `2026-10-13`: Fresh-bootstrap discovery needs every required Compose placeholder + - Context: the existing fresh-bootstrap wrapper failed before claiming a run or building images because its configuration-only service discovery supplied the mTLS certificate placeholder but omitted the required authored-world source receipt mount. + - Observation: Compose interpolation rejected the missing directory. The discovery command now supplies a configuration-only receipt path as well; this path is never used by the actual deployment, whose unchanged run-owned claim and capability create and bind the real receipt directory before Compose starts. + - Current status: the correction is being verified with the existing smoke contract and an actual fresh packaged player-flow run. Configuration parsing establishes no runtime or owner-provenance proof. diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index a5471ac095..30cf8d6f9d 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -52,7 +52,7 @@ if [[ -n "$FIREMUD_SMOKE_COMPOSE_SERVICES" ]]; then fi done <<<"$FIREMUD_SMOKE_COMPOSE_SERVICES" else - if ! compose_services_output="$(FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then + if ! compose_services_output="$(FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH=/tmp/firemud-compose-authored-world-source-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then echo "Docker Compose service discovery failed." >&2 exit 1 fi From 79fac839c5086571439e6e5e219eb58f2fa4f47f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:29:25 +1300 Subject: [PATCH 08/28] Record isolated Docker client credential-helper proof limitation --- design/project-management/ai-observations.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b2a97090c2..0ecbc70a70 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -240,3 +240,8 @@ Entry format: - Context: the existing fresh-bootstrap wrapper failed before claiming a run or building images because its configuration-only service discovery supplied the mTLS certificate placeholder but omitted the required authored-world source receipt mount. - Observation: Compose interpolation rejected the missing directory. The discovery command now supplies a configuration-only receipt path as well; this path is never used by the actual deployment, whose unchanged run-owned claim and capability create and bind the real receipt directory before Compose starts. - Current status: the correction is being verified with the existing smoke contract and an actual fresh packaged player-flow run. Configuration parsing establishes no runtime or owner-provenance proof. + +- `2026-10-13`: Native Linux Docker proof can still invoke a Windows credential helper + - Context: the claimed Gameplay fresh-bootstrap run rebuilt all service jars and images successfully, then failed before startup while pulling public Redis images. WSL reported `UtilAcceptVsock` and `accept4` timeout errors followed by a Docker credential lookup failure. + - Observation: using the native Linux Docker socket does not select a separate client credential configuration. A run-scoped private client configuration can omit unavailable Windows credential helpers while preserving static registry settings and Compose plugin discovery; the global client configuration need not change. + - Current status: the required packaged proof is being retried with that isolated configuration. This client failure does not establish an application failure or explain the earlier Testcontainers endpoint refusals. From 43d38b8aec41322eca4a2bb134739405b7d6267a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:36:55 +1300 Subject: [PATCH 09/28] Record qualified passive storage and fresh legacy player-flow proof --- .../microservices/entity-management-service/README.md | 2 +- .../microservices/entity-management-service/api-contracts.md | 2 +- .../entity-management-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 4 ++-- .../gameplay-rules-entities-and-effects.md | 4 ++-- .../implementation-tracking/player-access-and-session.md | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index 6cf82e0421..def19fe327 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Entity V1003–V1010 prepares opaque actor UUIDs, quarantine metadata, namespace/scope integrity, and assignment/receipt/roster storage while retaining legacy values. Manually composed source services and exact canonical repository readers are present without Spring registration, authenticated clients, or gRPC handlers. Existing legacy reads, roster listing, updates, cache access, scoped consumers, condition expiry, and cleanup retain develop behavior; this preparation does not enforce runtime quarantine or replace gameplay admission. Authenticated owner provenance, the real Game Session caller and execution replacement, and production activation remain unproved. Current boundary proof is pending under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); [Entity API Contracts](./api-contracts.md#implementation-status) owns the detailed source and wire contract. +Entity V1003–V1010 prepares opaque actor UUIDs, quarantine metadata, namespace/scope integrity, and assignment/receipt/roster storage while retaining legacy values. Manually composed source services and exact canonical repository readers are present without Spring registration, authenticated clients, or gRPC handlers. Existing legacy reads, roster listing, updates, cache access, scoped consumers, condition expiry, and cleanup retain develop behavior; this preparation does not enforce runtime quarantine or replace gameplay admission. Authenticated owner provenance, the real Game Session caller and execution replacement, and production activation remain unproved. Focused storage and unchanged legacy player-flow qualification is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); [Entity API Contracts](./api-contracts.md#implementation-status) owns the detailed source and wire contract. 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. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index a6e0470431..676d01b804 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; proof of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, remains pending under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. +Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. 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 a774f9f19b..e39f76a885 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -23,7 +23,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows; existing legacy consumers retain develop behavior and do not enforce that new metadata. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The source services are manually composed and unregistered; no authenticated transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). -- Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. The qualified donor's historical proof does not qualify this passive recut; its full check, fresh packaged player-flow proof, and actual-parent upgrade proof remain pending under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). +- Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. ## Architecture and Design Notes diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0ecbc70a70..2d7d1a89d2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -239,9 +239,9 @@ Entry format: - `2026-10-13`: Fresh-bootstrap discovery needs every required Compose placeholder - Context: the existing fresh-bootstrap wrapper failed before claiming a run or building images because its configuration-only service discovery supplied the mTLS certificate placeholder but omitted the required authored-world source receipt mount. - Observation: Compose interpolation rejected the missing directory. The discovery command now supplies a configuration-only receipt path as well; this path is never used by the actual deployment, whose unchanged run-owned claim and capability create and bind the real receipt directory before Compose starts. - - Current status: the correction is being verified with the existing smoke contract and an actual fresh packaged player-flow run. Configuration parsing establishes no runtime or owner-provenance proof. + - Current status: the existing smoke contract, shellcheck and actual configuration-only parsing pass. The subsequent fresh rebuilt packaged WebSocket and Telnet player-flow baselines pass with the unchanged real run-owned claim; this does not establish canonical owner provenance. - `2026-10-13`: Native Linux Docker proof can still invoke a Windows credential helper - Context: the claimed Gameplay fresh-bootstrap run rebuilt all service jars and images successfully, then failed before startup while pulling public Redis images. WSL reported `UtilAcceptVsock` and `accept4` timeout errors followed by a Docker credential lookup failure. - Observation: using the native Linux Docker socket does not select a separate client credential configuration. A run-scoped private client configuration can omit unavailable Windows credential helpers while preserving static registry settings and Compose plugin discovery; the global client configuration need not change. - - Current status: the required packaged proof is being retried with that isolated configuration. This client failure does not establish an application failure or explain the earlier Testcontainers endpoint refusals. + - Current status: the required packaged proof passes both transports with the isolated configuration and pinned public images. This client failure establishes neither an application regression nor a cause for the earlier Testcontainers endpoint refusals. 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 f505688b3c..6c0fa20fa6 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 @@ -28,7 +28,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` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `audited` - source and focused storage proof anchors are present, but this passive recut has no completed canonical full check, fresh packaged player-flow proof, or default combined-location/actual-parent upgrade proof. Historical donor runs do not qualify this boundary; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [Entity migrations](../../../services/entity-management-service/src/main/resources/db/migration/) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation: 234 Entity unit and 24 physical PostgreSQL integration cases pass with zero failures/errors/skips, including the default combined manifest and actual-parent retained upgrade. Fresh rebuilt images pass both transport LOGIN/PLAY/LOOK using unchanged develop gameplay consumers. This is not authenticated canonical owner/admission replacement; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [Entity migrations](../../../services/entity-management-service/src/main/resources/db/migration/) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | | 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. | @@ -113,7 +113,7 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof -- Current passive Entity preparation is unvalidated: V1003–V1010 follows unchanged develop V1/Saga1000–1002, and the qualified immutable donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` preserves the complete migration/storage source. That donor qualification does not apply to this recut. Main still owns the canonical full Entity check, documentation checks, fresh-image positive `LOGIN` → `PLAY` → `LOOK`, and default combined-location plus actual-parent upgrade proof. Authenticated owner/real caller/execution replacement and production activation remain unproved; no Game Design semantic or migration-order closure is claimed here. +- Current passive preparation at `79fac839c5086571439e6e5e219eb58f2fa4f47f` on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c`: Entity executed 234 unit cases in the first recut run and 24 physical PostgreSQL integration cases in the final run, all with zero failures, errors or skips; units were up-to-date in the final run. Default combined V1/Saga1000–1002/Entity1003–1010 fresh history and actual-parent retained-data upgrades passed, preserving installed ranks, scripts, checksums and success. Account's 15 new protection cases also passed locally; its broader local 236-case integration run had two unavailable endpoint fixtures (PostgreSQL refusal and Redis host-port timeout), so that full local gate failed. The identical Account/Common/proto/build input scope at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` passed source Validation Account job115335024215: 1295 unit cases with four existing filesystem skips, and 240 integration cases with zero failures/errors/skips, including both unavailable local suites. Main verified its own Account artifact11822625688 and matching inputs. Affected formatting, Checkstyle, SpotBugs and documentation checks pass; the final Account integration static/documentation gate passed in28s. The source-built, run-owned fresh-bootstrap proof rebuilt jars/images and passed WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK after the configuration-only discovery correction and isolated native Docker client recovery. These positive baseline results preserve legacy behavior; authenticated canonical owner/caller/controller/execution replacement and production activation remain unproved. The complete donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` retains later runtime obligations. Current published-head CI/reviews remain separate; no GDS semantic or ordering closure is claimed. - Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is1005 with no out-of-order migrations. The211unit cases retain the preceding executed-run attribution and were up-to-date in the final50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. 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 b8263e91e4..0492191468 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,7 +14,7 @@ The Account source-currentness/first-JOIN persistence stage builds on the tested The bounded V1003 receiving cut adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. -Fresh qualification on the receiving cut based on published Entity parent `6d93e3466b51079cb132d103b80b07dc1d3d0794` passes all 13 focused PostgreSQL cases with zero failures, errors or skips. The canonical gate also passes actual jOOQ generation, integration-source compilation, formatting, Checkstyle, SpotBugs, link checking and Markdown lint (2m47s; 86 tasks, 77 executed and 9 from cache). Only the two selected storage suites executed; this is not a full Account integration run or rebuilt packaged-runtime proof. The focused [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) defines eleven PostgreSQL cases, including unchanged retained rows/OIDs/checksums, complete original tuple and nested issuance binding, exact current replay, precision-sensitive expiry, source-writer exclusion, immutable rows and failed terminal release. The [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) defines two cases covering identity, pending exclusion, currentness and exact terminal integrity. These fixtures explicitly stipulate upstream Account/World/Game Session data with upstream producer triggers disabled; the protection and writer guards under test stay enabled. The fresh execution qualifies these storage fixtures only; historic whole-carrier results do not qualify additional cut behavior. Genuine source currentness, authenticated owner production and terminal settlement, continuous admission protection, activation, actor placement and region delivery remain unproved. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local storage consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). +Current preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passes all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh113-artifact manifest and unchanged actual112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact11822625688 with240integration0fail/error/skip and1295unit0fail/error/four existing filesystem skips. Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. The [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). ### Entity character-creation denial From 9783537b220fed96ee8d75f359cbb8b703f2f7a6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:22:38 +1300 Subject: [PATCH 10/28] fix: qualify passive protection acquisition and canonical assignment evidence --- design/project-management/ai-observations.md | 3 +- .../gameplay-rules-entities-and-effects.md | 8 +- .../player-access-and-session.md | 6 +- dev-tools/validation/check-flyway-versions.py | 16 + ...ginal_start_session_source_protections.sql | 67 +++- ...tionProtectionPostgresIntegrationTest.java | 346 +++++++++--------- ...sionProtectionPostgresIntegrationTest.java | 252 ++++++++++++- .../repository/CharacterRepository.java | 38 +- ...eededActorAssignmentGrantIntentDigest.java | 48 +-- .../PreseededActorAssignmentIntentDigest.java | 82 ++++- ...nedPreseededActorAssignmentCapability.java | 2 +- ...anonicalGameplayRosterIntegrationTest.java | 48 +++ ...eseededActorAssignmentIntegrationTest.java | 35 ++ .../PreseededActorAssignmentServiceTest.java | 4 + ...reseededActorAssignmentCapabilityTest.java | 42 ++- 15 files changed, 725 insertions(+), 272 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2d7d1a89d2..849b7429d8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -239,9 +239,10 @@ Entry format: - `2026-10-13`: Fresh-bootstrap discovery needs every required Compose placeholder - Context: the existing fresh-bootstrap wrapper failed before claiming a run or building images because its configuration-only service discovery supplied the mTLS certificate placeholder but omitted the required authored-world source receipt mount. - Observation: Compose interpolation rejected the missing directory. The discovery command now supplies a configuration-only receipt path as well; this path is never used by the actual deployment, whose unchanged run-owned claim and capability create and bind the real receipt directory before Compose starts. + - Expected pattern: keep configuration-only placeholders aligned with required Compose mount and environment inputs, then run the existing validate-only preflight when those inputs change. A successful parse establishes configuration completeness, not deployment or owner authority. - Current status: the existing smoke contract, shellcheck and actual configuration-only parsing pass. The subsequent fresh rebuilt packaged WebSocket and Telnet player-flow baselines pass with the unchanged real run-owned claim; this does not establish canonical owner provenance. - `2026-10-13`: Native Linux Docker proof can still invoke a Windows credential helper - Context: the claimed Gameplay fresh-bootstrap run rebuilt all service jars and images successfully, then failed before startup while pulling public Redis images. WSL reported `UtilAcceptVsock` and `accept4` timeout errors followed by a Docker credential lookup failure. - Observation: using the native Linux Docker socket does not select a separate client credential configuration. A run-scoped private client configuration can omit unavailable Windows credential helpers while preserving static registry settings and Compose plugin discovery; the global client configuration need not change. - - Current status: the required packaged proof passes both transports with the isolated configuration and pinned public images. This client failure establishes neither an application regression nor a cause for the earlier Testcontainers endpoint refusals. + - Current status: the required proof using packaged service artifacts passes both transports with the isolated configuration and pinned public images. This client failure establishes neither an application regression nor a cause for the earlier Testcontainers endpoint refusals. 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 6c0fa20fa6..fffcb64d26 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 @@ -28,7 +28,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` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation: 234 Entity unit and 24 physical PostgreSQL integration cases pass with zero failures/errors/skips, including the default combined manifest and actual-parent retained upgrade. Fresh rebuilt images pass both transport LOGIN/PLAY/LOOK using unchanged develop gameplay consumers. This is not authenticated canonical owner/admission replacement; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [Entity migrations](../../../services/entity-management-service/src/main/resources/db/migration/) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation: 234 Entity unit and 24 physical PostgreSQL integration cases pass with zero failures/errors/skips, including the default combined manifest and actual-parent retained upgrade. Fresh rebuilt images pass both transport LOGIN/PLAY/LOOK using unchanged develop gameplay consumers. This is not authenticated canonical owner/admission replacement; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | | 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. | @@ -113,9 +113,11 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof -- Current passive preparation at `79fac839c5086571439e6e5e219eb58f2fa4f47f` on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c`: Entity executed 234 unit cases in the first recut run and 24 physical PostgreSQL integration cases in the final run, all with zero failures, errors or skips; units were up-to-date in the final run. Default combined V1/Saga1000–1002/Entity1003–1010 fresh history and actual-parent retained-data upgrades passed, preserving installed ranks, scripts, checksums and success. Account's 15 new protection cases also passed locally; its broader local 236-case integration run had two unavailable endpoint fixtures (PostgreSQL refusal and Redis host-port timeout), so that full local gate failed. The identical Account/Common/proto/build input scope at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` passed source Validation Account job115335024215: 1295 unit cases with four existing filesystem skips, and 240 integration cases with zero failures/errors/skips, including both unavailable local suites. Main verified its own Account artifact11822625688 and matching inputs. Affected formatting, Checkstyle, SpotBugs and documentation checks pass; the final Account integration static/documentation gate passed in28s. The source-built, run-owned fresh-bootstrap proof rebuilt jars/images and passed WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK after the configuration-only discovery correction and isolated native Docker client recovery. These positive baseline results preserve legacy behavior; authenticated canonical owner/caller/controller/execution replacement and production activation remain unproved. The complete donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` retains later runtime obligations. Current published-head CI/reviews remain separate; no GDS semantic or ordering closure is claimed. +- Current passive preparation at `79fac839c5086571439e6e5e219eb58f2fa4f47f` on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c`: Entity executed 234 unit cases in the first recut run and 24 physical PostgreSQL integration cases in the final run, all with zero failures, errors or skips; units were up-to-date in the final run. Default combined V1/Saga1000–1002/Entity1003–1010 fresh history and actual-parent retained-data upgrades passed, preserving installed ranks, scripts, checksums and success. Account's 15 new protection cases also passed locally; its broader local 236-case integration run had two unavailable endpoint fixtures (PostgreSQL refusal and Redis host-port timeout), so that full local gate failed. The identical Account/Common/proto/build input scope at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` passed source Validation Account job 115335024215: 1295 unit cases with four existing filesystem skips, and 240 integration cases with zero failures/errors/skips, including both unavailable local suites. Main verified its own Account artifact 11822625688 and matching inputs. Affected formatting, Checkstyle, SpotBugs and documentation checks pass; the final Account integration static/documentation gate passed in 28s. The source-built, run-owned fresh-bootstrap proof rebuilt jars/images and passed WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK after the configuration-only discovery correction and isolated native Docker client recovery. These positive baseline results preserve legacy behavior; authenticated canonical owner/caller/controller/execution replacement and production activation remain unproved. The complete donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` retains later runtime obligations. Current published-head CI/reviews remain separate; no GDS semantic or ordering closure is claimed. -- Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is1005 with no out-of-order migrations. The211unit cases retain the preceding executed-run attribution and were up-to-date in the final50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. +- Subsequent review corrections on develop `18f8063306c2ddb4337646de50b73619915a0e25` pass the full Entity gate: 236 unit cases executed in the first correction run and 26 physical PostgreSQL cases executed in the final gate, with zero failures, errors or skips. The new PostgreSQL proof checks Spring-proxy rejection without a caller-owned writable transaction and overlapping roster reads while preserving assignment writer exclusion. Both assignment digest paths use the same ordered encoder with literal `SHARED`/`ISOLATED` digest vectors, and run-owned capabilities admit release references through the documented 1,024-character bound. The canonical 79-leaf implementation-tracker check passes with actual migration file anchors. Account correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). These are bounded passive storage/source corrections; canonical runtime consumers and genuine owner admission remain open. + +- Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is 1005 with no out-of-order migrations. The 211 unit cases retain the preceding executed-run attribution and were up-to-date in the final 50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. - The integrated passive receiver review corrections on develop `b95aade1546a1d90fde3e884b14eef8190314864` passed `spotlessApply :common-platform-core:check -PfullCheck linkCheck lintMarkdown --continue` locally in 1m 38s (213 tasks). Common-platform-core executed 370 tests with zero failures, errors, or skips, including branding DELETE identity, strict command schema integers, exact policy/template revision provenance, and both owner-inventory mutation round trips and rejection cases. This focused run qualifies these passive corrections only; exact published-head CI remains separate and no producer, owner protection, terminal composition, or activation proof is claimed. 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 0492191468..fe2b426ce2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,7 +14,9 @@ The Account source-currentness/first-JOIN persistence stage builds on the tested The bounded V1003 receiving cut adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. -Current preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passes all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh113-artifact manifest and unchanged actual112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact11822625688 with240integration0fail/error/skip and1295unit0fail/error/four existing filesystem skips. Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. The [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). +The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). + +The subsequent Hosted/CLI correction on develop `18f8063306c2ddb4337646de50b73619915a0e25` executed 18 focused Account PostgreSQL cases with zero failures, errors or skips. Acquisition now rejects admission data that cannot satisfy immutable settlement bounds; committed activation fixtures run the acquisition, source-child and deferred-completeness guards. The proof includes the 256-source boundary, canonical Base64 and UTF-16 ordering, a complete activation tuple above 135,168 bytes, and settlement after lease expiry. Actual jOOQ generation, compilation, integration Checkstyle and SpotBugs, formatting and documentation checks passed. This corrects the bounded fixture proof; the older broad source-CI counts remain historical and do not qualify the changed SQL or establish genuine owner production. ### Entity character-creation denial @@ -150,7 +152,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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. `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java) | [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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. | +| `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; genuine owner acquisition and authenticated terminal-settlement producers remain open. | | `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`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index a464eaa827..dca5fa2471 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -251,6 +251,19 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str if event_base_ref(str(event_path)) != expected: raise AssertionError(f"unexpected event base for {event}") + # CI passes push metadata through the environment; the explicit option + # must handle the same unborn-branch sentinel without reading Git history. + for explicit in (False, True): + environment = dict(os.environ) + environment.pop("GITHUB_EVENT_PATH", None) + environment["FIREMUD_FLYWAY_BASE_REF"] = "0" * 40 + command = [sys.executable, str(Path(__file__).resolve()), "--root", tmp] + if explicit: + command.extend(["--base-ref", "0" * 40]) + result = subprocess.run(command, env=environment, capture_output=True, text=True) + if result.returncode or "Parent frontier comparison" not in result.stdout: + raise AssertionError(f"unborn explicit={explicit}: {result.stdout} {result.stderr}") + print("Flyway migration sanity checker self-test passed.") @@ -285,6 +298,9 @@ def main() -> int: root = args.root.resolve() try: base_ref = args.base_ref or event_base_ref(os.environ.get("GITHUB_EVENT_PATH")) + # All input paths use GitHub's all-zero sentinel for a new branch. + if base_ref == "0" * 40: + base_ref = None parent = parent_snapshot(root, base_ref) if base_ref else None issues, project_count, file_count = collect_issues(current_snapshot(root), parent) except (ValueError, OSError, TypeError) as error: diff --git a/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql index 1529026b92..ae48d7bb70 100644 --- a/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql +++ b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql @@ -28,8 +28,8 @@ CREATE TABLE account_start_session_admission_protections ( capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), - world_admission_hold_identity_bytes BYTEA NOT NULL CHECK (octet_length(world_admission_hold_identity_bytes) BETWEEN 1 AND 262144), - request_binding_bytes BYTEA NOT NULL CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 1048576), + world_admission_hold_identity_bytes BYTEA NOT NULL CHECK (octet_length(world_admission_hold_identity_bytes) BETWEEN 1 AND 65536), + request_binding_bytes BYTEA NOT NULL CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 786432), request_binding_digest VARCHAR(71) NOT NULL CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), producer_xid BIGINT NOT NULL DEFAULT txid_current(), @@ -102,6 +102,10 @@ DECLARE source_bytes BYTEA; source_key_value TEXT; keys TEXT[]; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + source_bytes_total BIGINT := 0; + canonical_request TEXT; BEGIN SELECT * INTO STRICT capture FROM account_start_session_authority_captures WHERE control_plane_request_id = original.control_plane_request_id; @@ -110,6 +114,31 @@ BEGIN OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id THEN RAISE EXCEPTION 'Admission protection requires the exact original source snapshot' USING ERRCODE = '23514'; END IF; + IF octet_length(capture.canonical_capture_bytes) NOT BETWEEN 1 AND 262144 + OR octet_length(capture.canonical_snapshot_bytes) NOT BETWEEN 1 AND 245760 + OR jsonb_typeof(snapshot_value->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_value->'sourceVector') NOT BETWEEN 1 AND 256 THEN + RAISE EXCEPTION 'Admission protection source capture exceeds settlement bounds' USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Admission protection source vector has a non-string member' USING ERRCODE = '23514'; + END IF; + source_bytes := decode(source_value #>> '{}', 'base64'); + source_bytes_total := source_bytes_total + octet_length(source_bytes); + IF octet_length(source_bytes) NOT BETWEEN 1 AND 131072 + OR source_bytes_total > 4194304 + OR regexp_replace(encode(source_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM source_value #>> '{}' THEN + RAISE EXCEPTION 'Admission protection source vector exceeds canonical settlement bounds' USING ERRCODE = '23514'; + END IF; + current_sort_key := account_publication_authorization_source_sort_key( + account_start_session_world_participation_source_key(source_bytes)); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Admission protection source vector is duplicated or out of order' USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + END LOOP; keys := account_start_session_world_participation_lock_sources(snapshot_value); PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); SELECT * INTO STRICT capture FROM account_start_session_authority_captures @@ -187,6 +216,35 @@ BEGIN OR request_value->>'worldAdmissionHoldIdentityBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') THEN RAISE EXCEPTION 'Admission request binding differs from exact immutable selectors' USING ERRCODE = '23514'; END IF; + canonical_request := '{"accountRedemptionProjectionBytesBase64":"' + || regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + || '","accountWorldParticipationFence":"' + || original.account_world_participation_fence::TEXT + || '","accountWorldParticipationId":"' + || original.account_world_participation_id::TEXT + || '","gameSessionOwnerAttemptId":"' + || original.game_session_owner_attempt_id::TEXT + || '","gameSessionOwnerFence":"' + || original.game_session_owner_fence::TEXT + || '","gameSessionOwnerMutationId":"' + || original.game_session_owner_mutation_id::TEXT + || '","originalLeaseExpiresAt":"' + || to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + || '","originalPostAuthorizationTupleBytesBase64":"' + || regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-request/v1"' + || ',"worldAdmissionHoldIdentityBytesBase64":"' + || regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') + || '"}'; + IF octet_length(original.request_binding_bytes) NOT BETWEEN 1 AND 786432 + OR octet_length(original.world_admission_hold_identity_bytes) NOT BETWEEN 1 AND 65536 + OR convert_to(canonical_request, 'UTF8') IS DISTINCT FROM original.request_binding_bytes + OR original.request_binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.request_binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission request is not its exact canonical binding' + USING ERRCODE = '23514'; + END IF; + hold_value := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; hold_request := convert_from(decode(hold_value->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; IF hold_value->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' @@ -195,6 +253,7 @@ BEGIN OR EXISTS (SELECT 1 FROM jsonb_each(hold_value) field WHERE jsonb_typeof(field.value) <> 'string') OR (hold_value->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID OR (hold_value->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_value->>'requestBytesBase64' IS DISTINCT FROM regexp_replace(encode(decode(hold_value->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') OR hold_value->>'holdBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') OR hold_request->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' OR hold_request->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace @@ -850,7 +909,7 @@ CREATE TABLE account_start_session_activation_protections ( original_post_authorization_tuple BYTEA NOT NULL CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), account_redemption_projection BYTEA NOT NULL - CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 135168), + CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 262144), game_session_owner_mutation_id UUID NOT NULL UNIQUE CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), game_session_owner_attempt_id UUID NOT NULL @@ -1290,7 +1349,7 @@ BEGIN SELECT COALESCE( jsonb_agg( to_jsonb(replace(replace(encode(source.source_evidence, 'base64'), E'\n', ''), E'\r', '')) - ORDER BY source.source_key), + ORDER BY account_publication_authorization_source_sort_key(source.source_key)), '[]'::JSONB) INTO expected_source_vector FROM account_start_session_activation_protection_sources source diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 89f9c3c574..52131fd8be 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -37,9 +37,10 @@ /** * Runs V1003 against the actual Account PostgreSQL schema and assembled source-writer guard. The - * integrity and currentness fixtures seed related owner rows with producer triggers disabled; they - * prove SQL currentness/exclusion/immutability only, not authenticated activation-protection - * production. + * integrity and currentness fixtures seed related owner rows with upstream producer triggers + * disabled. Protection acquisition, child completeness, settlement and source-writer guards remain + * enabled; they prove SQL currentness/exclusion/immutability only, not authenticated + * activation-protection production. */ @Testcontainers(disabledWithoutDocker = true) class AccountStartSessionActivationProtectionPostgresIntegrationTest { @@ -52,159 +53,33 @@ class AccountStartSessionActivationProtectionPostgresIntegrationTest { @Test void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() throws Exception { Fixture fixture = fixture(); - UUID participationId = UUID.randomUUID(); - UUID ownerMutationId = UUID.randomUUID(); - UUID ownerAttemptId = UUID.randomUUID(); - UUID tenantId = UUID.randomUUID(); - UUID gameInstanceId = UUID.randomUUID(); - UUID activationRequestId = UUID.randomUUID(); - byte[] captureReference = bytes("capture-reference"); - byte[] operationIdentity = bytes("{\"schema\":\"activation-operation-test/v1\"}"); - String captureDigest = hash(captureReference); - String operationDigest = "sha256:" + hash(operationIdentity); - OffsetDateTime expiry = + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(10), 135500); + byte[] requestBinding = current.requestBytes(); + Map request = readJson(requestBinding); + UUID activationRequestId = UUID.fromString((String) request.get("worldActivationRequestId")); + byte[] preparingEvidence = + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")); + byte[] captureReference = bytes("{}"); + String operationDigest = current.operationIdentityDigest(); + assertThat( + Base64.getDecoder() + .decode((String) request.get("accountRedemptionProjectionBytesBase64")) + .length) + .isGreaterThan(135168) + .isLessThanOrEqualTo(262144); + acquireProtection(fixture, current); + var sources = fixture .dsl() - .fetchSingle("SELECT clock_timestamp() - INTERVAL '1 minute'") - .get(0, OffsetDateTime.class); - OffsetDateTime acquiredAt = expiry.minusMinutes(1); - String expiryText = timestamp(expiry); - SourceEvidence sourceEvidence = - new SourceEvidence( - SourceKind.ACCOUNT, - tenantId.toString(), - "2", - "17", - null, - null, - bytes("captured activation source")); - String sourceKey = sourceEvidence.key(); - byte[] sourceEvidenceBytes = sourceEvidence.canonicalBytes(); - byte[] tuple = bytes("synthetic original tuple"); - byte[] projection = bytes("synthetic Account redemption projection"); - byte[] launchRead = bytes("synthetic authenticated STARTING launch read"); - byte[] preparingEvidence = - jsonBytes( - Map.of( - "schema", - "world-canonical-instance-lifecycle-evidence/v1", - "request", - Map.of( - "readRequestId", - UUID.randomUUID().toString(), - "controlPlaneRequestId", - fixture.requestId(), - "targetNamespace", - "test", - "canonicalTenantId", - tenantId.toString(), - "canonicalGameInstanceId", - gameInstanceId.toString()), - "lifecycleStatus", - "PREPARING", - "lifecycleEpoch", - 12, - "rowVersion", - 19)); - byte[] requestBinding = - activationRequest( - tuple, - projection, - ownerMutationId, - ownerAttemptId, - 11L, - expiryText, - participationId, - 7L, - launchRead, - activationRequestId, - preparingEvidence); - String requestDigest = "sha256:" + hash(requestBinding); - - fixture - .transaction() - .executeWithoutResult( - status -> { - fixture - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - sourceKey); - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - insert( - fixture.dsl(), - "account_start_session_activation_protections", - "control_plane_request_id", - fixture.requestId(), - "account_world_participation_id", - participationId, - "account_world_participation_fence", - 7L, - "original_post_authorization_tuple", - tuple, - "account_redemption_projection", - projection, - "game_session_owner_mutation_id", - ownerMutationId, - "game_session_owner_attempt_id", - ownerAttemptId, - "game_session_owner_fence", - 11L, - "original_lease_expires_at", - expiry, - "acquired_at", - acquiredAt, - "target_namespace", - "test", - "canonical_tenant_id", - tenantId, - "canonical_game_instance_id", - gameInstanceId, - "world_activation_request_id", - activationRequestId, - "game_session_launch_read_evidence", - launchRead, - "world_preparing_evidence", - preparingEvidence, - "capture_source_version", - 13L, - "capture_source_fence", - 17L, - "capture_sha256", - captureDigest, - "capture_reference_bytes", - captureReference, - "capture_reference_sha256", - captureDigest, - "operation_identity_bytes", - operationIdentity, - "operation_identity_digest", - operationDigest, - "request_binding_bytes", - requestBinding, - "request_binding_digest", - requestDigest); - var parent = - fixture - .dsl() - .fetchSingle( - "SELECT activation_protection_id, activation_protection_fence, " - + "acquired_at " - + "FROM account_start_session_activation_protections " - + "WHERE control_plane_request_id = ?", - fixture.requestId()); - UUID id = parent.get("activation_protection_id", UUID.class); - insert( - fixture.dsl(), - "account_start_session_activation_protection_sources", - "activation_protection_id", - id, - "source_key", - sourceKey, - "source_evidence", - sourceEvidenceBytes); - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .fetch( + "SELECT source_key, source_evidence FROM account_start_session_activation_protection_sources " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)"); + assertThat(sources).hasSize(2); + String sourceKey = sources.get(0).get("source_key", String.class); + byte[][] sourceEvidenceBytes = + sources.stream() + .map(row -> row.get("source_evidence", byte[].class)) + .toArray(byte[][]::new); var stored = fixture @@ -248,9 +123,15 @@ void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() thr sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); + fixture + .dsl() + .fetch( + "SELECT pg_sleep(GREATEST(0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", + current.expiryText()); + // This synthetic SQL receipt proves only that V1003 permits a source writer after an immutable // terminal-shaped row is committed. It is not a typed receipt or authenticated World producer - // proof. The original Account lease is deliberately expired before this settlement insert. + // proof. The original lease has expired before settlement insertion. OffsetDateTime retainedAcquiredAt = stored.get("acquired_at", OffsetDateTime.class); long protectionFence = stored.get("activation_protection_fence", Long.class); byte[] accountEvidenceBytes = @@ -520,7 +401,7 @@ private static byte[] accountEvidence( OffsetDateTime acquiredAt, byte[] requestBytes, byte[] captureReference, - byte[] sourceEvidence) + byte[]... sourceEvidence) throws Exception { Map value = new LinkedHashMap<>(); value.put("schema", "account-start-session-activation-protection-evidence/v1"); @@ -534,7 +415,7 @@ private static byte[] accountEvidence( value.put("originalSourceCaptureReferenceSha256", hash(captureReference)); value.put( "sourceEvidenceVector", - java.util.List.of(Base64.getEncoder().encodeToString(sourceEvidence))); + java.util.Arrays.stream(sourceEvidence).map(Base64.getEncoder()::encodeToString).toList()); return jsonBytes(value); } @@ -636,6 +517,11 @@ private static void assertCurrentnessRejected( private static CurrentnessCase currentnessCase(Fixture fixture, Instant originalLease) throws Exception { + return currentnessCase(fixture, originalLease, 0); + } + + private static CurrentnessCase currentnessCase( + Fixture fixture, Instant originalLease, int padding) throws Exception { UUID tenantId = UUID.randomUUID(); UUID gameInstanceId = UUID.randomUUID(); UUID participationId = UUID.randomUUID(); @@ -663,11 +549,19 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original .withZone(ZoneOffset.UTC) .format(normalizedLease); - byte[] preAuthorization = bytes("{}"); + Map preAuthorizationValue = + Map.of( + "scope", + Map.of("targetNamespace", "test", "tenantId", tenantId.toString()), + "fixturePadding", + "x".repeat(Math.min(6000, padding))); + byte[] preAuthorization = jsonBytes(preAuthorizationValue); Map bundleValue = Map.of( "issuanceOperationIdentity", - Map.of("issuanceOperationId", issuanceOperationId.toString())); + Map.of("issuanceOperationId", issuanceOperationId.toString()), + "fixturePadding", + "x".repeat(padding - Math.min(6000, padding))); byte[] authorityBundle = jsonBytes(bundleValue); byte[] tuple = jsonBytes( @@ -675,7 +569,7 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original "controlPlaneRequestId", requestId, "preAuthorizationReservationTuple", - Map.of(), + preAuthorizationValue, "authorizationReferenceFingerprint", fingerprint, "issuanceFence", @@ -685,16 +579,25 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original // Current-use integrity preserves the complete stipulated original tuple without scalarizing // it. byte[] projection = tuple.clone(); - SourceEvidence sourceEvidence = - new SourceEvidence( - SourceKind.ACCOUNT, - tenantId.toString(), - "2", - "17", - null, - null, - bytes("activation-source")); - String sourceKey = sourceEvidence.key(); + // Java String ordering is UTF-16: the supplementary key precedes the BMP private-use key. + var sourceEvidence = + java.util.List.of( + new SourceEvidence( + SourceKind.HOSTED_TERMS, + tenantId + "-terms-\uD800\uDC00", + "2", + "17", + null, + null, + bytes("supplementary source")), + new SourceEvidence( + SourceKind.HOSTED_TERMS, + tenantId + "-terms-\uE000", + "2", + "17", + null, + null, + bytes("BMP source"))); byte[] snapshot = jsonBytes( Map.of( @@ -703,8 +606,9 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original "controlPlaneRequestId", requestId, "sourceVector", - java.util.List.of( - Base64.getEncoder().encodeToString(sourceEvidence.canonicalBytes())))); + sourceEvidence.stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList())); byte[] captureReference = bytes("{}"); String captureDigest = hash(captureReference); String snapshotDigest = hash(snapshot); @@ -740,8 +644,30 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original .dsl() .execute( "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - sourceKey); + sourceEvidence.get(0).key()); + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceEvidence.get(1).key()); fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenantId, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenantId.toString()); insert( fixture.dsl(), "account_start_session_authority_captures", @@ -868,15 +794,17 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original preparationInput, "preparation_input_digest", preparationDigest); - insert( - fixture.dsl(), - "account_start_session_world_participation_sources", - "participation_id", - participationId, - "source_key", - sourceKey, - "source_evidence", - sourceEvidence.canonicalBytes()); + for (SourceEvidence source : sourceEvidence) { + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + participationId, + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } insert( fixture.dsl(), "account_start_session_world_original_attempt_evidence", @@ -934,6 +862,60 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original requestBytes, operationIdentity, operationDigest, ownerAttemptId, expiryText); } + private static void acquireProtection(Fixture fixture, CurrentnessCase current) { + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + """ + INSERT INTO account_start_session_activation_protections( + control_plane_request_id, account_world_participation_id, account_world_participation_fence, + original_post_authorization_tuple, account_redemption_projection, + game_session_owner_mutation_id, game_session_owner_attempt_id, game_session_owner_fence, + original_lease_expires_at, target_namespace, canonical_tenant_id, canonical_game_instance_id, + world_activation_request_id, game_session_launch_read_evidence, world_preparing_evidence, + capture_source_version, capture_source_fence, capture_sha256, + capture_reference_bytes, capture_reference_sha256, operation_identity_bytes, + operation_identity_digest, request_binding_bytes, request_binding_digest) + SELECT w.control_plane_request_id, w.participation_id, w.participation_fence, + w.original_post_authorization_tuple, w.original_post_authorization_tuple, + o.game_session_owner_mutation_id, o.game_session_owner_attempt_id, o.game_session_owner_fence, + o.original_lease_expires_at, w.target_namespace, w.canonical_tenant_id, w.canonical_game_instance_id, + (r.value->>'worldActivationRequestId')::uuid, + decode(r.value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'), + decode(r.value->>'preparingEvidenceBytesBase64', 'base64'), + c.source_version, c.source_fence, c.canonical_sha256, + c.canonical_capture_bytes, c.canonical_sha256, ?, ?, ?, ? + FROM account_start_session_world_participations w + JOIN account_start_session_world_original_attempt_evidence o USING(participation_id) + JOIN account_start_session_authority_captures c USING(control_plane_request_id) + CROSS JOIN (SELECT convert_from(?::bytea, 'UTF8')::jsonb AS value) r + WHERE w.participation_id = (r.value->>'accountWorldParticipationId')::uuid + """, + current.operationIdentityBytes(), + current.operationIdentityDigest(), + current.requestBytes(), + "sha256:" + hash(current.requestBytes()), + current.requestBytes()); + fixture + .dsl() + .execute( + """ + INSERT INTO account_start_session_activation_protection_sources( + activation_protection_id, source_key, source_evidence) + SELECT p.activation_protection_id, s.source_key, s.source_evidence + FROM account_start_session_activation_protections p + JOIN account_start_session_world_participation_sources s + ON s.participation_id = p.account_world_participation_id + WHERE p.operation_identity_digest = ? + """, + current.operationIdentityDigest()); + }); + } + private static byte[] activationRequest( CurrentnessCase current, String ownerAttemptId, String expiry, String worldStatus) throws Exception { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 8792e629aa..a965d0d621 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -901,21 +901,255 @@ void currentRecoveryRechecksDatabaseExpiryAfterTheCallerWaitsForOriginalCaptureL .isFalse(); } + @Test + void acquisitionRejectsUnsettleableHoldRequestAndSourceSnapshotBounds() throws Exception { + Fixture fixture = fixture(); + byte[] oversizedHold = + bytes(new String(fixture.hold(), StandardCharsets.UTF_8) + " ".repeat(65537)); + Map oversizedHoldRequest = + tools.jackson.databind.json.JsonMapper.builder() + .build() + .readValue(fixture.request(), new tools.jackson.core.type.TypeReference<>() {}); + oversizedHoldRequest.put("worldAdmissionHoldIdentityBytesBase64", base64(oversizedHold)); + assertDatabaseGuardFailure( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insertProtection(fixture, 11L, oversizedHold, json(oversizedHoldRequest))), + "23514"); + assertDatabaseGuardFailure( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insertProtection( + fixture, + 11L, + fixture.hold(), + bytes( + new String(fixture.request(), StandardCharsets.UTF_8) + + " ".repeat(786433)))), + "23514"); + + for (List vector : + List.of( + List.of(), + java.util.Collections.nCopies(257, base64(fixture.source().canonicalBytes())), + List.of(base64(new byte[131073])), + List.of(base64(fixture.source().canonicalBytes()) + "\n"))) { + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + vector))); + assertDatabaseGuardFailure(() -> acquire(fixture), "23514"); + } + assertDatabaseGuardFailure( + () -> + replaceSnapshot( + fixture, + bytes( + new String( + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + List.of(base64(fixture.source().canonicalBytes())))), + StandardCharsets.UTF_8) + + " ".repeat(245761))), + "23514"); + } + + @Test + void acquisitionAccepts256CompleteSourcesAndRejects257CompleteSources() { + for (int sourceCount : List.of(256, 257)) { + Fixture fixture = fixture(); + var sources = new java.util.ArrayList(); + sources.add(fixture.source()); + for (int index = 1; index < sourceCount; index++) { + sources.add( + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "bounded-source-" + index, + "1", + "1", + null, + null, + bytes("captured source"))); + } + sources.sort(java.util.Comparator.comparing(SourceEvidence::key)); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + for (SourceEvidence source : sources) { + if (source.key().equals(fixture.source().key())) continue; + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + fixture.worldId(), + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + sources.stream().map(source -> base64(source.canonicalBytes())).toList()))); + if (sourceCount == 256) { + acquire(fixture); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_start_session_admission_protection_sources WHERE protection_id = ?", + fixture.protectionId()) + .get(0, Long.class)) + .isEqualTo(256L); + } else { + assertDatabaseGuardFailure(() -> acquire(fixture), "23514"); + } + } + } + + @Test + void acquisitionRequiresCanonicalUtf16OrderForMultipleUnicodeSources() { + Fixture fixture = fixture(); + var supplementary = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "terms-\uD800\uDC00", + "1", + "1", + null, + null, + bytes("supplementary")); + var bmp = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "terms-\uE000", "1", "1", null, null, bytes("BMP")); + var sources = + java.util.stream.Stream.of(fixture.source(), supplementary, bmp) + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList(); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + for (SourceEvidence source : List.of(supplementary, bmp)) { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + fixture.worldId(), + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + var reversed = new java.util.ArrayList<>(sources); + java.util.Collections.reverse(reversed); + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + reversed.stream().map(source -> base64(source.canonicalBytes())).toList()))); + assertDatabaseGuardFailure(() -> acquire(fixture), "23514"); + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + sources.stream().map(source -> base64(source.canonicalBytes())).toList()))); + acquire(fixture); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_start_session_admission_protection_sources WHERE protection_id = ?", + fixture.protectionId()) + .get(0, Long.class)) + .isEqualTo(3L); + } + + private static void assertDatabaseGuardFailure(Runnable operation, String expectedSqlState) { + assertThatThrownBy(operation::run) + .isInstanceOf(RuntimeException.class) + .satisfies(failure -> assertDatabaseGuardFailure(failure, "", expectedSqlState)); + } + + private static void replaceSnapshot(Fixture fixture, byte[] snapshot) { + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_authority_captures SET canonical_snapshot_bytes = ?, snapshot_sha256 = ? WHERE control_plane_request_id = ?", + snapshot, + hash(snapshot), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + } + private static void acquire(Fixture fixture) { fixture .transaction() .executeWithoutResult( status -> { insertProtection(fixture, 11L); - insert( - fixture.dsl(), - "account_start_session_admission_protection_sources", - "protection_id", - fixture.protectionId(), - "source_key", - fixture.source().key(), - "source_evidence", - fixture.source().canonicalBytes()); + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_sources(protection_id, source_key, source_evidence) SELECT ?, source_key, source_evidence FROM account_start_session_world_participation_sources WHERE participation_id = ?", + fixture.protectionId(), + fixture.worldId()); }); } 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 83f7402391..d0c322cc67 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 @@ -44,6 +44,7 @@ import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Repository @@ -705,7 +706,7 @@ static Optional onlyOneAssignmentMatch(List matchingOperatio * Callers use this only inside the same writable transaction that records an applicability hold, * so actor changes either win first and invalidate the receipt or observe the durable hold. */ - @Transactional + @Transactional(propagation = Propagation.MANDATORY) public Optional lockCurrentPreseededActorAssignmentReceipt( UUID assignmentUuid, UUID canonicalAccountUuid, UUID characterUuid, String intentDigest) { if (!org.springframework.transaction.support.TransactionSynchronizationManager @@ -806,11 +807,7 @@ private void enrollNamespace(PreseededActorAssignmentOwnerEvidence evidence) { } private long requireEntityTenantRow(UUID tenantUuid) { - dsl.insertInto(TENANT_IDENTITIES) - .set(CANONICAL_TENANT_UUID, tenantUuid) - .onConflict(CANONICAL_TENANT_UUID) - .doNothing() - .execute(); + ensureEntityTenantRow(tenantUuid); Long rowId = dsl.select(ENTITY_TENANT_ROW_ID) .from(TENANT_IDENTITIES) @@ -823,6 +820,30 @@ private long requireEntityTenantRow(UUID tenantUuid) { return rowId; } + private long requireEntityTenantRowForRoster(UUID tenantUuid) { + ensureEntityTenantRow(tenantUuid); + // Assignment's FOR UPDATE still excludes this reader while the immutable mapping stays stable. + Long rowId = + dsl.select(ENTITY_TENANT_ROW_ID) + .from(TENANT_IDENTITIES) + .where(CANONICAL_TENANT_UUID.eq(tenantUuid)) + .forKeyShare() + .fetchOne(ENTITY_TENANT_ROW_ID); + if (rowId == null || rowId <= 0L) { + throw new IllegalStateException( + "CANONICAL_GAMEPLAY_ROSTER_ENTITY_TENANT_MAPPING_UNAVAILABLE"); + } + return rowId; + } + + private void ensureEntityTenantRow(UUID tenantUuid) { + dsl.insertInto(TENANT_IDENTITIES) + .set(CANONICAL_TENANT_UUID, tenantUuid) + .onConflict(CANONICAL_TENANT_UUID) + .doNothing() + .execute(); + } + private boolean hasOwnerResolvedAccountNamespace(PreseededActorAssignmentOwnerEvidence evidence) { UUID existingActor = dsl.select(CHARACTERS.CHARACTER_UUID) @@ -945,7 +966,7 @@ public CanonicalGameplayRosterSnapshot captureCanonicalGameplayRosterSnapshot( CanonicalGameplayRosterTarget target = ownerEvidence.target(); lockCanonicalRosterNamespace(target); - requireEntityTenantRow(target.tenantUuid()); + requireEntityTenantRowForRoster(target.tenantUuid()); List currentActors = readCurrentCanonicalRoster(request.canonicalAccountUuid(), target); @@ -1075,6 +1096,7 @@ private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) .doNothing() .execute(); + // Assignment takes FOR UPDATE on this row before actor insertion. String enrolledScope = dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) @@ -1085,7 +1107,7 @@ private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) .and( ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( target.playableStateNamespaceId()))) - .forUpdate() + .forShare() .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); if (!target.playableStateScope().name().equals(enrolledScope)) { throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java index baba148e4b..8b67f21c89 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java @@ -1,56 +1,10 @@ package net.firedevops.firemud.entitymanagement.service; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; - /** Computes the assignment digest from the caller target before any owner reads are performed. */ final class PreseededActorAssignmentGrantIntentDigest { - private static final String DOMAIN = "firemud.entity.preseeded-actor-assignment.v4"; - private PreseededActorAssignmentGrantIntentDigest() {} static String compute(PreseededActorAssignmentRequest request) { - var target = request.expectedTarget(); - try { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (DataOutputStream output = new DataOutputStream(bytes)) { - write(output, DOMAIN); - write(output, request.assignmentUuid().toString()); - write(output, request.canonicalAccountUuid().toString()); - write(output, request.corePayload().actorKind().name()); - write(output, request.corePayload().displayName()); - write(output, target.canonicalTenantUuid().toString()); - write(output, target.realmUuid().toString()); - write(output, target.worldSlug()); - write(output, target.realmSlug()); - write(output, target.gameInstanceId()); - write(output, Long.toString(target.catalogRevision())); - write(output, target.canonicalVersionUuid().toString()); - write(output, target.frozenPolicyDigest()); - write(output, target.playableStateNamespaceId().toString()); - write(output, target.publishedReleaseBundleRef()); - write(output, target.playableStateScope().name()); - write( - output, - PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY.name()); - } - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } catch (IOException exception) { - throw new IllegalStateException("Unable to encode assignment grant intent", exception); - } - } - - private static void write(DataOutputStream output, String value) throws IOException { - byte[] encoded = value.getBytes(StandardCharsets.UTF_8); - output.writeInt(encoded.length); - output.write(encoded); + return PreseededActorAssignmentIntentDigest.computeGrant(request); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java index 1b5752cf03..1f8c9eb82b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java @@ -7,6 +7,8 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; /** Entity-side canonical digest for the immutable assignment intent. */ final class PreseededActorAssignmentIntentDigest { @@ -14,8 +16,56 @@ final class PreseededActorAssignmentIntentDigest { private PreseededActorAssignmentIntentDigest() {} + static String computeGrant(PreseededActorAssignmentRequest request) { + var target = request.expectedTarget(); + return encode( + request, + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY); + } + static String compute( PreseededActorAssignmentRequest request, PreseededActorAssignmentOwnerEvidence evidence) { + return encode( + request, + evidence.canonicalTenantUuid(), + evidence.realmUuid(), + evidence.worldSlug(), + evidence.realmSlug(), + evidence.gameInstanceId(), + evidence.catalogRevision(), + evidence.canonicalVersionUuid(), + evidence.frozenPolicyDigest(), + evidence.playableStateNamespaceId(), + evidence.publishedReleaseBundleRef(), + evidence.playableStateScope(), + evidence.entryPolicy()); + } + + private static String encode( + PreseededActorAssignmentRequest request, + UUID canonicalTenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + String gameInstanceId, + long catalogRevision, + UUID canonicalVersionUuid, + String frozenPolicyDigest, + UUID playableStateNamespaceId, + String publishedReleaseBundleRef, + PlayableStateScope playableStateScope, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy entryPolicy) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (DataOutputStream output = new DataOutputStream(bytes)) { @@ -24,18 +74,18 @@ static String compute( write(output, request.canonicalAccountUuid().toString()); write(output, request.corePayload().actorKind().name()); write(output, request.corePayload().displayName()); - write(output, evidence.canonicalTenantUuid().toString()); - write(output, evidence.realmUuid().toString()); - write(output, evidence.worldSlug()); - write(output, evidence.realmSlug()); - write(output, evidence.gameInstanceId()); - write(output, Long.toString(evidence.catalogRevision())); - write(output, evidence.canonicalVersionUuid().toString()); - write(output, evidence.frozenPolicyDigest()); - write(output, evidence.playableStateNamespaceId().toString()); - write(output, evidence.publishedReleaseBundleRef()); - write(output, evidence.playableStateScope().name()); - write(output, evidence.entryPolicy().name()); + write(output, canonicalTenantUuid.toString()); + write(output, realmUuid.toString()); + write(output, worldSlug); + write(output, realmSlug); + write(output, gameInstanceId); + write(output, Long.toString(catalogRevision)); + write(output, canonicalVersionUuid.toString()); + write(output, frozenPolicyDigest); + write(output, playableStateNamespaceId.toString()); + write(output, publishedReleaseBundleRef); + write(output, scopeText(playableStateScope)); + write(output, entryPolicy.name()); } return HexFormat.of() .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); @@ -46,6 +96,14 @@ static String compute( } } + private static String scopeText(PlayableStateScope scope) { + return switch (scope) { + case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; + case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; + default -> throw new IllegalArgumentException("Unsupported playable-state scope"); + }; + } + private static void write(DataOutputStream output, String value) throws IOException { byte[] encoded = value.getBytes(StandardCharsets.UTF_8); output.writeInt(encoded.length); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java index ae90c2ebcd..102bfe2dac 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java @@ -525,7 +525,7 @@ private static String requiredText(JsonNode root, String field) { } String parsed = value.textValue(); if (parsed.isBlank() - || parsed.length() > 256 + || parsed.length() > 1024 || !parsed.equals(parsed.trim()) || parsed.indexOf('\n') >= 0 || parsed.indexOf('\r') >= 0) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java index 2c848fb966..dfcc4310aa 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java @@ -38,6 +38,8 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -67,6 +69,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private CharacterRepository characterRepository; @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; private UUID accountUuid; @@ -301,6 +304,51 @@ void concurrentIdenticalReadsReuseOnePersistedSnapshotIdentity() throws Exceptio } } + @Test + void differentAccountRosterCaptureCanFinishWhileAnotherReaderHoldsItsTransaction() + throws Exception { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + UUID otherAccountUuid = UUID.randomUUID(); + createPersistedActor(accountUuid, exactTarget, 71L, "First Actor"); + createPersistedActor(otherAccountUuid, exactTarget, 72L, "Second Actor"); + CountDownLatch firstRead = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + new TransactionTemplate(transactionManager) + .execute( + ignored -> { + CanonicalGameplayRosterSnapshot snapshot = + readRoster(accountUuid, exactTarget); + firstRead.countDown(); + try { + if (!releaseFirst.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "First roster transaction was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return snapshot; + })); + assertThat(firstRead.await(10, TimeUnit.SECONDS)).isTrue(); + + Future second = + executor.submit(() -> readRoster(otherAccountUuid, exactTarget)); + CanonicalGameplayRosterSnapshot secondResult = second.get(5, TimeUnit.SECONDS); + assertThat(secondResult.actors()).hasSize(1); + releaseFirst.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS).actors()).hasSize(1); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + private CanonicalGameplayRosterSnapshot readRoster( UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { UUID requestUuid = UUID.randomUUID(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 05a2b96b1c..3e900f290d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -23,6 +24,7 @@ import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; @@ -45,6 +47,9 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -82,6 +87,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private CharacterRepository characterRepository; @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @@ -96,6 +102,35 @@ void createIsolatedOwnerProofIdentities() { namespaceUuid = UUID.randomUUID(); } + @Test + void receiptLockRequiresCallerOwnedWritableTransactionThroughRepositoryProxy() { + UUID absentActor = UUID.randomUUID(); + assertThatThrownBy( + () -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64))) + .isInstanceOf(IllegalTransactionStateException.class); + + TransactionTemplate writable = new TransactionTemplate(transactionManager); + Optional absentReceipt = + writable.execute( + ignored -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64))); + assertThat(absentReceipt).isEmpty(); + + TransactionTemplate readOnly = new TransactionTemplate(transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + ignored -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable hold transaction"); + } + @Test void postgresMigrationInstallsAndEnforcesDeferredAssignmentForeignKeys() { assign( diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java index f20ed8774e..1dfc81483b 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java @@ -510,6 +510,10 @@ void intentDigestBindsFullTargetAndPayloadButIgnoresEligibilityRefreshEvidence() request.expectedTarget()); String digest = PreseededActorAssignmentIntentDigest.compute(request, baseline); + assertThat(digest) + .isEqualTo("59f2041020ab6231ec26fe838bb70b25df509bfd0fa7f4bc78fe85575a1286b8"); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedScope)) + .isEqualTo("89b56ed7c981e381017285ef4916928e2e357413f11cf909fb6e07f848f86b5c"); assertThat(PreseededActorAssignmentIntentDigest.compute(request, reevaluated)) .isEqualTo(digest); assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedCatalog)) diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java index 7e5b8f569c..88801be61c 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java @@ -44,6 +44,34 @@ void parsesExactGrantAndBindsRunProjectPeerAssignmentTargetPayloadAndTlsTrustRoo assertThat(capability.matchesOwnerTarget(request(), ownerEvidence())).isTrue(); } + @Test + void grantDigestUsesCanonicalShortScopeTextForBothScopes() { + assertThat(PreseededActorAssignmentGrantIntentDigest.compute(request())) + .isEqualTo("59f2041020ab6231ec26fe838bb70b25df509bfd0fa7f4bc78fe85575a1286b8"); + PreseededActorAssignmentRequest isolated = + request("release-bundle/test", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); + assertThat(PreseededActorAssignmentGrantIntentDigest.compute(isolated)) + .isEqualTo("89b56ed7c981e381017285ef4916928e2e357413f11cf909fb6e07f848f86b5c"); + assertThat(parse(validJson(isolated)).matchesRequest(isolated)).isTrue(); + } + + @Test + void permitsFullReleaseReferenceBoundWithoutRelaxingTargetValidation() { + for (int length : new int[] {257, 1024}) { + PreseededActorAssignmentRequest longReleaseRef = + request("r".repeat(length), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(parse(validJson(longReleaseRef)).matchesRequest(longReleaseRef)).isTrue(); + } + assertThatThrownBy( + () -> request("r".repeat(1025), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + assertInvalid( + validJson() + .replace( + "\"publishedReleaseBundleRef\": \"release-bundle/test\"", + "\"publishedReleaseBundleRef\": \"" + "r".repeat(1025) + "\"")); + } + @Test void rejectsUnknownDuplicateAndChangedIntentFields() { assertInvalid( @@ -247,6 +275,11 @@ private static Set readOnlyFilePermissions() { } private static PreseededActorAssignmentRequest request() { + return request("release-bundle/test", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + private static PreseededActorAssignmentRequest request( + String releaseRef, PlayableStateScope scope) { return new PreseededActorAssignmentRequest( ASSIGNMENT_UUID, ACCOUNT_UUID, @@ -261,8 +294,8 @@ private static PreseededActorAssignmentRequest request() { UUID.fromString("17000000-0000-4000-8000-000000000017"), "2".repeat(64), NAMESPACE_UUID, - "release-bundle/test", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + releaseRef, + scope)); } private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { @@ -292,7 +325,10 @@ private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { } private static String validJson() { - PreseededActorAssignmentRequest request = request(); + return validJson(request()); + } + + private static String validJson(PreseededActorAssignmentRequest request) { PreseededActorAssignmentExpectedTarget target = request.expectedTarget(); return String.join( "%n", From 4e45c706c79a898d82f6c6902ba8bec0f611f2d5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:25:55 +1300 Subject: [PATCH 11/28] fix: make Flyway fixture subprocess failure handling explicit --- dev-tools/validation/check-flyway-versions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index dca5fa2471..4f1ab5f92a 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -260,7 +260,7 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str command = [sys.executable, str(Path(__file__).resolve()), "--root", tmp] if explicit: command.extend(["--base-ref", "0" * 40]) - result = subprocess.run(command, env=environment, capture_output=True, text=True) + result = subprocess.run(command, check=False, env=environment, capture_output=True, text=True) if result.returncode or "Parent frontier comparison" not in result.stdout: raise AssertionError(f"unborn explicit={explicit}: {result.stdout} {result.stderr}") From 68ee9a6094181d233988c47588a66dceb7dbe6ea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 04:40:19 +1300 Subject: [PATCH 12/28] fix: retain canonical isolated selected-assignment reads --- ...meplayRosterSelectedAssignmentService.java | 4 +- ...ayRosterSelectedAssignmentServiceTest.java | 73 ++++++++++++++++--- 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java index b31dc3e8a6..7ccab4f45b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java @@ -2,7 +2,6 @@ import java.util.Objects; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Non-admitting read of the exact committed assignment for a selected PRESEEDED actor. */ @@ -93,8 +92,7 @@ private static void requireNoAmbientTransaction() { } private static void requireSupportedTarget(CanonicalGameplayRosterTarget target) { - if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY - || target.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { throw new UnsupportedOperationException("SELECTED_PRESEEDED_ASSIGNMENT_TARGET_UNSUPPORTED"); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java index 8390971388..f07dc37ab7 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java @@ -19,12 +19,18 @@ class CanonicalGameplayRosterSelectedAssignmentServiceTest { @Test void resolvesCurrentTargetThenReturnsOnlyTheExactHistoricalAssignmentReference() { + assertResolvesCurrentTarget(target()); + assertResolvesCurrentTarget( + withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + } + + private static void assertResolvesCurrentTarget(CanonicalGameplayRosterTarget target) { CanonicalGameplayRosterOwnerEvidencePort ownerPort = mock(CanonicalGameplayRosterOwnerEvidencePort.class); CharacterRepository repository = mock(CharacterRepository.class); CanonicalGameplayRosterSelectedAssignmentService service = new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); - CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target); CanonicalGameplayRosterReadRequest ownerRequest = new CanonicalGameplayRosterReadRequest( request.requestUuid(), @@ -120,8 +126,24 @@ void ownerFailureAndRequestAccountOrTargetMismatchFailBeforeRepositoryRead() { evidence( ownerRequest, withScope(request.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)), - UnsupportedOperationException.class, - "SELECTED_PRESEEDED_ASSIGNMENT_TARGET_UNSUPPORTED"); + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + CanonicalGameplayRosterSelectedAssignmentReadRequest isolatedRequest = + request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + CanonicalGameplayRosterReadRequest isolatedOwnerRequest = + new CanonicalGameplayRosterReadRequest( + isolatedRequest.requestUuid(), + isolatedRequest.canonicalAccountUuid(), + isolatedRequest.expectedTarget(), + isolatedRequest.playerExecutionContext()); + assertOwnerMismatchBeforeRepository( + isolatedRequest, + evidence( + isolatedOwnerRequest, + withScope( + isolatedRequest.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); assertOwnerMismatchBeforeRepository( request, evidence(ownerRequest, withCatalogRevision(request.expectedTarget(), 4L)), @@ -130,7 +152,7 @@ void ownerFailureAndRequestAccountOrTargetMismatchFailBeforeRepositoryRead() { } @Test - void unsupportedCallerPolicyAndScopeFailBeforeOwnerResolution() { + void unsupportedCallerPolicyFailsBeforeOwnerResolution() { CanonicalGameplayRosterOwnerEvidencePort ownerPort = mock(CanonicalGameplayRosterOwnerEvidencePort.class); CharacterRepository repository = mock(CharacterRepository.class); @@ -143,12 +165,6 @@ void unsupportedCallerPolicyAndScopeFailBeforeOwnerResolution() { request( withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy( - () -> - service.read( - request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)))) - .isInstanceOf(UnsupportedOperationException.class); - verifyNoInteractions(ownerPort, repository); } @@ -213,6 +229,43 @@ void missingOrInvalidStoredAssignmentFailsClosed() { .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_UNAVAILABLE"); } + @Test + void isolatedSelectionRejectsSharedAssignmentReceipt() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = + request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + PreseededActorAssignmentExpectedTarget isolatedTarget = + assignmentTarget(request.expectedTarget()); + PreseededActorAssignmentExpectedTarget sharedTarget = + assignmentTarget( + withScope(request.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(ownerPort.resolveCurrentTarget(ownerRequest)) + .thenReturn(evidence(ownerRequest, request.expectedTarget())); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn(snapshot(request)); + when(repository.readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + isolatedTarget, + request.expectedTarget().publishedOwnerProofDigest())) + .thenReturn(Optional.of(receipt(request, sharedTarget))); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_RECEIPT_MISMATCH"); + } + @Test void changedSnapshotOrActorAbsentFromItFailsBeforeReceiptRead() { CanonicalGameplayRosterOwnerEvidencePort ownerPort = From 4925747b7eca6a4b5c9e043479492813bf6a6c1e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 05:14:59 +1300 Subject: [PATCH 13/28] fix: isolate canonical actor storage from legacy numeric consumers --- .../runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 4 +- .../ActorActiveConditionRepository.java | 95 ++-- .../ActorResourceStateRepository.java | 84 +++- .../CharacterEquipmentRepository.java | 9 +- .../repository/CharacterFriendRepository.java | 57 ++- .../repository/CharacterRepository.java | 33 +- .../repository/InventoryEntryRepository.java | 8 +- ...eseededActorAssignmentIntegrationTest.java | 416 ++++++++++++++++++ .../RetainedActorIdentityIntegrationTest.java | 25 +- 10 files changed, 649 insertions(+), 84 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 e39f76a885..5047468f68 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -21,7 +21,7 @@ This document defines Entity Management’s runtime model, persistence ownership - 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. -- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows; existing legacy consumers retain develop behavior and do not enforce that new metadata. +- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude new `OWNER_RESOLVED` actors, including updates and condition expiry. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The source services are manually composed and unregistered; no authenticated transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. 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 fffcb64d26..5f99b982fe 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 @@ -28,7 +28,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` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation: 234 Entity unit and 24 physical PostgreSQL integration cases pass with zero failures/errors/skips, including the default combined manifest and actual-parent retained upgrade. Fresh rebuilt images pass both transport LOGIN/PLAY/LOOK using unchanged develop gameplay consumers. This is not authenticated canonical owner/admission replacement; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation: the current corrected Entity gate passes unit and physical PostgreSQL integration cases with zero failures/errors/skips, including the default combined manifest and actual-parent retained upgrade; executed counts and run attribution are recorded under Validation and Proof. Fresh rebuilt images pass both transport LOGIN/PLAY/LOOK using unchanged develop gameplay consumers. This is not authenticated canonical owner/admission replacement; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-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); [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) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql) | [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); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | | 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. | @@ -117,6 +117,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Subsequent review corrections on develop `18f8063306c2ddb4337646de50b73619915a0e25` pass the full Entity gate: 236 unit cases executed in the first correction run and 26 physical PostgreSQL cases executed in the final gate, with zero failures, errors or skips. The new PostgreSQL proof checks Spring-proxy rejection without a caller-owned writable transaction and overlapping roster reads while preserving assignment writer exclusion. Both assignment digest paths use the same ordered encoder with literal `SHARED`/`ISOLATED` digest vectors, and run-owned capabilities admit release references through the documented 1,024-character bound. The canonical 79-leaf implementation-tracker check passes with actual migration file anchors. Account correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). These are bounded passive storage/source corrections; canonical runtime consumers and genuine owner admission remain open. +- The final legacy-bridge isolation correction passes the full Entity gate with 237 unit and 27 physical PostgreSQL integration cases, zero failures, errors or skips. The colliding numeric-tenant fixture proves that canonical actors and their inventory, equipment, friend, resource and condition rows are hidden from legacy readers, guarded writes reject canonical stored parents even when a legacy parent is supplied, and expiry preserves canonical conditions. Ordinary legacy reads, inserts, updates, deletes and expiry remain usable; exact canonical UUID, receipt and roster reads remain usable. The inventory-bearing positive case also exposed and corrected a missing inventory-version projection. A fresh, uncached TCP proto-generation and Java-compilation proof passes; the earlier source Runtime compiler failure remains unreproduced and does not supply current packaged runtime proof. New published-head CI and the remaining allocated Hosted checkpoint remain required. + - Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is 1005 with no out-of-order migrations. The 211 unit cases retain the preceding executed-run attribution and were up-to-date in the final 50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. - The integrated passive receiver review corrections on develop `b95aade1546a1d90fde3e884b14eef8190314864` passed `spotlessApply :common-platform-core:check -PfullCheck linkCheck lintMarkdown --continue` locally in 1m 38s (213 tasks). Common-platform-core executed 370 tests with zero failures, errors, or skips, including branding DELETE identity, strict command schema integers, exact policy/template revision provenance, and both owner-inventory mutation round trips and rejection cases. This focused run qualifies these passive corrections only; exact published-head CI remains separate and no producer, owner protection, terminal composition, or activation proof is claimed. 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..5b4c3aceb8 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,14 +2,18 @@ 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; import java.util.List; import java.util.Optional; import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; +import org.jooq.Condition; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -32,6 +36,7 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) + .and(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID)) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -60,7 +65,8 @@ public List findActiveForCharacter( .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) - .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId))) + .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId)) + .and(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) .limit(1) .fetchOne(this::toEntity)); @@ -69,36 +75,63 @@ public List findActiveForCharacter( public ActorActiveCondition save(ActorActiveCondition entity) { if (entity.getId() == null) { Long id = - dsl.insertInto(ACTOR_ACTIVE_CONDITIONS) - .set(ACTOR_ACTIVE_CONDITIONS.TENANT_ID, entity.getTenantId()) - .set(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) - .set(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, entity.getCharacterId()) - .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.CREATED_AT, toOffsetDateTime(entity.getCreatedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + dsl.insertInto( + ACTOR_ACTIVE_CONDITIONS, + ACTOR_ACTIVE_CONDITIONS.TENANT_ID, + ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY, + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, + ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, + ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, + ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, + ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, + ACTOR_ACTIVE_CONDITIONS.STARTED_AT, + ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, + ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, + ACTOR_ACTIVE_CONDITIONS.CREATED_AT, + ACTOR_ACTIVE_CONDITIONS.UPDATED_AT) + .select( + dsl.select( + DSL.val(entity.getTenantId()), + DSL.val(entity.getPlayableStateKey()), + DSL.val(entity.getCharacterId()), + DSL.val(entity.getConditionKey()), + DSL.val(entity.getStackCount()), + DSL.val(entity.getSourceType()), + DSL.val(entity.getSourceId()), + DSL.val(toOffsetDateTime(entity.getStartedAt())), + DSL.val(toOffsetDateTime(entity.getExpiresAt())), + DSL.val(entity.getEffectPayloadJson()), + DSL.val(toOffsetDateTime(entity.getCreatedAt())), + DSL.val(toOffsetDateTime(entity.getUpdatedAt()))) + .where(legacyCharacter(DSL.val(entity.getCharacterId())))) .returningResult(ACTOR_ACTIVE_CONDITIONS.ID) .fetchOne(ACTOR_ACTIVE_CONDITIONS.ID); + if (id == null) { + throw new IllegalStateException("Legacy condition character is unavailable"); + } 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 updated = + 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(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Legacy condition row is unavailable"); + } entity.setVersion(entity.getVersion() + 1); return entity; } @@ -109,10 +142,18 @@ 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(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .execute(); } + private static Condition legacyCharacter(Field characterId) { + return DSL.exists( + DSL.selectOne() + .from(CHARACTERS) + .where(CHARACTERS.ID.eq(characterId).and(CharacterRepository.legacyCharacterRow()))); + } + 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/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 478bd81341..9ef93f2567 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,16 @@ 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.Condition; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -29,7 +33,8 @@ 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(legacyCharacter(ACTOR_RESOURCE_STATES.CHARACTER_ID))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } @@ -37,37 +42,70 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO public ActorResourceState save(ActorResourceState entity) { if (entity.getId() == null) { Long id = - dsl.insertInto(ACTOR_RESOURCE_STATES) - .set(ACTOR_RESOURCE_STATES.TENANT_ID, entity.getTenantId()) - .set(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) - .set(ACTOR_RESOURCE_STATES.CHARACTER_ID, entity.getCharacterId()) - .set(ACTOR_RESOURCE_STATES.STAT_KEY, entity.getStatKey()) - .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.CREATED_AT, toOffsetDateTime(entity.getCreatedAt())) - .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + dsl.insertInto( + ACTOR_RESOURCE_STATES, + ACTOR_RESOURCE_STATES.TENANT_ID, + ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY, + ACTOR_RESOURCE_STATES.CHARACTER_ID, + ACTOR_RESOURCE_STATES.STAT_KEY, + ACTOR_RESOURCE_STATES.CURRENT_VALUE, + ACTOR_RESOURCE_STATES.MAX_VALUE, + ACTOR_RESOURCE_STATES.BASE_VALUE, + ACTOR_RESOURCE_STATES.SOURCE_TYPE, + ACTOR_RESOURCE_STATES.SOURCE_ID, + ACTOR_RESOURCE_STATES.CREATED_AT, + ACTOR_RESOURCE_STATES.UPDATED_AT) + .select( + dsl.select( + DSL.val(entity.getTenantId()), + DSL.val(entity.getPlayableStateKey()), + DSL.val(entity.getCharacterId()), + DSL.val(entity.getStatKey()), + DSL.val(entity.getCurrentValue()), + DSL.val(entity.getMaxValue()), + DSL.val(entity.getBaseValue()), + DSL.val(entity.getSourceType()), + DSL.val(entity.getSourceId()), + DSL.val(toOffsetDateTime(entity.getCreatedAt())), + DSL.val(toOffsetDateTime(entity.getUpdatedAt()))) + .where(legacyCharacter(DSL.val(entity.getCharacterId())))) .returningResult(ACTOR_RESOURCE_STATES.ID) .fetchOne(ACTOR_RESOURCE_STATES.ID); + if (id == null) { + throw new IllegalStateException("Legacy resource character is unavailable"); + } 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 updated = + 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(legacyCharacter(ACTOR_RESOURCE_STATES.CHARACTER_ID))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Legacy resource row is unavailable"); + } entity.setVersion(entity.getVersion() + 1); return entity; } + private static Condition legacyCharacter(Field characterId) { + return DSL.exists( + DSL.selectOne() + .from(CHARACTERS) + .where(CHARACTERS.ID.eq(characterId).and(CharacterRepository.legacyCharacterRow()))); + } + 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..6d7c2e5470 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(CharacterRepository.legacyCharacterRow()))); 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(CharacterRepository.legacyCharacterRow())) .orderBy(CHARACTER_EQUIPMENT.SLOT.asc()) .limit( JooqEntityManagementRepositorySupport.limitOrDefault(pageable, Integer.MAX_VALUE)) @@ -83,7 +85,8 @@ public long countByCharacterTenantId(Long tenantId) { .from(CHARACTER_EQUIPMENT) .join(CHARACTERS) .on(CHARACTER_EQUIPMENT.CHARACTER_ID.eq(CHARACTERS.ID)) - .where(CHARACTERS.TENANT_ID.eq(tenantId))); + .where( + CHARACTERS.TENANT_ID.eq(tenantId).and(CharacterRepository.legacyCharacterRow()))); } private CharacterEquipmentEntry toEntity(Record record) { 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..61afc5ee8d 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,14 +1,18 @@ 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.Optional; import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; +import org.jooq.Condition; import org.jooq.DSLContext; +import org.jooq.Field; 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 +29,12 @@ public CharacterFriendRepository(DSLContext dsl) { } public Page findByIdCharacterId(Long characterId, Pageable pageable) { - long total = dsl.fetchCount(CHARACTER_FRIEND, CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)); + Condition condition = + CHARACTER_FRIEND.CHARACTER_ID.eq(characterId).and(legacyFriendEndpoints()); + 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)) @@ -37,7 +43,8 @@ public Page findByIdCharacterId(Long characterId, Pageable page } public long countByTenantId(Long tenantId) { - return dsl.fetchCount(CHARACTER_FRIEND, CHARACTER_FRIEND.TENANT_ID.eq(tenantId)); + return dsl.fetchCount( + CHARACTER_FRIEND, CHARACTER_FRIEND.TENANT_ID.eq(tenantId).and(legacyFriendEndpoints())); } public Optional findById(CharacterFriendKey key) { @@ -47,18 +54,33 @@ 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(legacyFriendEndpoints())) .fetchOne(this::toEntity)); } public CharacterFriend save(CharacterFriend entity) { if (findById(entity.getId()).isEmpty()) { - dsl.insertInto(CHARACTER_FRIEND) - .set(CHARACTER_FRIEND.CHARACTER_ID, entity.getId().getCharacterId()) - .set(CHARACTER_FRIEND.FRIEND_ID, entity.getId().getFriendId()) - .set(CHARACTER_FRIEND.TENANT_ID, entity.getTenantId()) - .set(CHARACTER_FRIEND.CREATED_AT, toLocalDateTime(entity.getCreatedAt())) - .execute(); + int inserted = + dsl.insertInto( + CHARACTER_FRIEND, + CHARACTER_FRIEND.CHARACTER_ID, + CHARACTER_FRIEND.FRIEND_ID, + CHARACTER_FRIEND.TENANT_ID, + CHARACTER_FRIEND.CREATED_AT) + .select( + dsl.select( + DSL.val(entity.getId().getCharacterId()), + DSL.val(entity.getId().getFriendId()), + DSL.val(entity.getTenantId()), + DSL.val(toLocalDateTime(entity.getCreatedAt()))) + .where( + legacyCharacter(DSL.val(entity.getId().getCharacterId())) + .and(legacyCharacter(DSL.val(entity.getId().getFriendId()))))) + .execute(); + if (inserted != 1) { + throw new IllegalStateException("Legacy friend endpoints are unavailable"); + } } return entity; } @@ -69,10 +91,23 @@ 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(legacyFriendEndpoints())) .execute(); } + private static Condition legacyFriendEndpoints() { + return legacyCharacter(CHARACTER_FRIEND.CHARACTER_ID) + .and(legacyCharacter(CHARACTER_FRIEND.FRIEND_ID)); + } + + private static Condition legacyCharacter(Field characterId) { + return DSL.exists( + DSL.selectOne() + .from(CHARACTERS) + .where(CHARACTERS.ID.eq(characterId).and(CharacterRepository.legacyCharacterRow()))); + } + 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 d0c322cc67..c94f061dc7 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 @@ -149,9 +149,15 @@ public CharacterRepository(DSLContext dsl) { this.dsl = dsl; } + static Condition legacyCharacterRow() { + return CHARACTERS.ACTOR_IDENTITY_STATUS.ne(ActorIdentityStatus.OWNER_RESOLVED.name()); + } + 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(legacyCharacterRow())) + .fetchOne(this::toEntity); if (character == null) { return Optional.empty(); } @@ -161,6 +167,7 @@ public Optional findWithInventoryById(Long id) { INVENTORY.CHARACTER_ID, INVENTORY.ITEM_ID, INVENTORY.QUANTITY, + INVENTORY.VERSION, ITEMS.ID, ITEMS.TENANT_ID, ITEMS.VERSION_ID, @@ -184,13 +191,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(legacyCharacterRow())) + .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(legacyCharacterRow())) .fetchOne(this::toEntity)); } @@ -203,7 +217,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(legacyCharacterRow())) .fetchOne(this::toEntity)); } @@ -214,7 +229,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(legacyCharacterRow()); long total = dsl.fetchCount(CHARACTERS, condition); var content = dsl.selectFrom(CHARACTERS) @@ -237,13 +253,14 @@ 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(legacyCharacterRow())) .limit(1) .fetchOne(this::toEntity)); } public long countByTenantId(Long tenantId) { - return dsl.fetchCount(CHARACTERS, CHARACTERS.TENANT_ID.eq(tenantId)); + return dsl.fetchCount(CHARACTERS, CHARACTERS.TENANT_ID.eq(tenantId).and(legacyCharacterRow())); } public long countQuarantinedByTenantId(Long tenantId) { @@ -1307,7 +1324,7 @@ public Character save(Character entity) { .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())) + .where(CHARACTERS.ID.eq(entity.getId()).and(legacyCharacterRow())) .execute(); return findById(entity.getId()).orElseThrow(); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java index c552c4ebd8..c6662bf066 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java @@ -40,17 +40,19 @@ public long countByCharacterTenantId(Long tenantId) { .from(INVENTORY) .join(CHARACTERS) .on(INVENTORY.CHARACTER_ID.eq(CHARACTERS.ID)) - .where(CHARACTERS.TENANT_ID.eq(tenantId))); + .where( + CHARACTERS.TENANT_ID.eq(tenantId).and(CharacterRepository.legacyCharacterRow()))); } private Page fetchPage(Condition condition, Pageable pageable) { + Condition legacyCondition = condition.and(CharacterRepository.legacyCharacterRow()); long total = dsl.fetchCount( dsl.selectOne() .from(INVENTORY) .join(CHARACTERS) .on(INVENTORY.CHARACTER_ID.eq(CHARACTERS.ID)) - .where(condition)); + .where(legacyCondition)); var content = dsl.select( INVENTORY.CHARACTER_ID, @@ -79,7 +81,7 @@ private Page fetchPage(Condition condition, Pageable pageable) { .on(INVENTORY.CHARACTER_ID.eq(CHARACTERS.ID)) .join(ITEMS) .on(INVENTORY.ITEM_ID.eq(ITEMS.ID)) - .where(condition) + .where(legacyCondition) .orderBy(INVENTORY.ITEM_ID.asc()) .limit( JooqEntityManagementRepositorySupport.limitOrDefault(pageable, Integer.MAX_VALUE)) diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 3e900f290d..7c8e6a633f 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -21,7 +21,22 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +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.entity.CharacterFriend; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; +import net.firedevops.firemud.entitymanagement.repository.ActorActiveConditionRepository; +import net.firedevops.firemud.entitymanagement.repository.ActorResourceStateRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterEquipmentRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterFriendRepository; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.repository.InventoryEntryRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterExecutionContext; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; @@ -42,6 +57,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.dao.DataAccessException; +import org.springframework.data.domain.Pageable; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; @@ -86,6 +102,11 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private CharacterRepository characterRepository; + @Autowired private CharacterFriendRepository characterFriendRepository; + @Autowired private ActorResourceStateRepository actorResourceStateRepository; + @Autowired private ActorActiveConditionRepository actorActiveConditionRepository; + @Autowired private InventoryEntryRepository inventoryEntryRepository; + @Autowired private CharacterEquipmentRepository characterEquipmentRepository; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private PlatformTransactionManager transactionManager; @@ -655,6 +676,401 @@ void committedReceiptIsExactReplayStableAndDeniedForChangedOrQuarantinedActor() assertConflictWithoutActorDisclosure(changedRelease); } + @Test + void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Canonical Actor", + "a"); + Long entityTenantRowId = + jdbcTemplate.queryForObject( + "SELECT entity_tenant_row_id FROM entity_tenant_identities " + + "WHERE canonical_tenant_uuid = ?", + Long.class, + tenantUuid); + Long canonicalCharacterId = + jdbcTemplate.queryForObject( + "SELECT id FROM characters WHERE character_uuid = ?", + Long.class, + assigned.characterUuid()); + Long legacyCharacterId = + jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + + "VALUES (23, 'Legacy Actor', ?, 'shared-live') RETURNING id", + Long.class, + entityTenantRowId); + Long itemId = + jdbcTemplate.queryForObject( + "INSERT INTO items (name, tenant_id) VALUES ('Legacy Item', ?) RETURNING id", + Long.class, + entityTenantRowId); + for (Long characterId : List.of(canonicalCharacterId, legacyCharacterId)) { + jdbcTemplate.update( + "INSERT INTO inventory (character_id, item_id, quantity) VALUES (?, ?, 1)", + characterId, + itemId); + jdbcTemplate.update( + "INSERT INTO character_equipment (character_id, slot, item_id) " + + "VALUES (?, 'hand', ?)", + characterId, + itemId); + } + Long legacyFriendId = + jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + + "VALUES (24, 'Legacy Friend', ?, 'shared-live') RETURNING id", + Long.class, + entityTenantRowId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id) VALUES (?, ?, ?)", + legacyCharacterId, + legacyFriendId, + entityTenantRowId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id) VALUES (?, ?, ?)", + canonicalCharacterId, + legacyFriendId, + entityTenantRowId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id) VALUES (?, ?, ?)", + legacyCharacterId, + canonicalCharacterId, + entityTenantRowId); + Long canonicalResourceId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_resource_states " + + "(tenant_id, playable_state_key, character_id, stat_key, current_value) " + + "VALUES (?, ?, ?, 'focus', 5) RETURNING id", + Long.class, + entityTenantRowId, + namespaceUuid.toString(), + canonicalCharacterId); + Long legacyResourceId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_resource_states " + + "(tenant_id, playable_state_key, character_id, stat_key, current_value) " + + "VALUES (?, 'shared-live', ?, 'focus', 7) RETURNING id", + Long.class, + entityTenantRowId, + legacyCharacterId); + Instant expiry = Instant.parse("2030-01-01T00:00:00Z"); + Long canonicalConditionId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_active_conditions " + + "(tenant_id, playable_state_key, character_id, condition_key, source_type, " + + "source_id, expires_at) VALUES (?, ?, ?, 'shielded', 'fixture', 'canonical', ?) " + + "RETURNING id", + Long.class, + entityTenantRowId, + namespaceUuid.toString(), + canonicalCharacterId, + java.time.OffsetDateTime.ofInstant(expiry, java.time.ZoneOffset.UTC)); + Long legacyConditionId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_active_conditions " + + "(tenant_id, playable_state_key, character_id, condition_key, source_type, " + + "source_id, expires_at) VALUES (?, 'shared-live', ?, 'shielded', 'fixture', " + + "'legacy', ?) RETURNING id", + Long.class, + entityTenantRowId, + legacyCharacterId, + java.time.OffsetDateTime.ofInstant(expiry, java.time.ZoneOffset.UTC)); + + assertThat(characterRepository.findById(canonicalCharacterId)).isEmpty(); + assertThat(characterRepository.findWithInventoryById(canonicalCharacterId)).isEmpty(); + assertThat(characterRepository.findByIdAndTenantId(canonicalCharacterId, entityTenantRowId)) + .isEmpty(); + assertThat( + characterRepository.findByIdAndTenantIdAndPlayableStateKey( + canonicalCharacterId, entityTenantRowId, namespaceUuid.toString())) + .isEmpty(); + assertThat( + characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( + entityTenantRowId, 23L, namespaceUuid.toString(), Pageable.unpaged())) + .isEmpty(); + assertThat( + characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( + entityTenantRowId, namespaceUuid.toString(), "Canonical Actor")) + .isEmpty(); + assertThat(characterRepository.countByTenantId(entityTenantRowId)).isEqualTo(2); + assertThat(characterRepository.countQuarantinedByTenantId(entityTenantRowId)).isEqualTo(2); + assertThat(inventoryEntryRepository.countByCharacterTenantId(entityTenantRowId)).isEqualTo(1); + assertThat(characterEquipmentRepository.countByCharacterTenantId(entityTenantRowId)) + .isEqualTo(1); + assertThat( + inventoryEntryRepository.findByIdCharacterId(canonicalCharacterId, Pageable.unpaged())) + .isEmpty(); + assertThat( + inventoryEntryRepository.findByIdCharacterIdAndCharacterTenantId( + canonicalCharacterId, entityTenantRowId, Pageable.unpaged())) + .isEmpty(); + assertThat( + characterEquipmentRepository.findByIdCharacterIdAndCharacterTenantId( + canonicalCharacterId, entityTenantRowId, Pageable.unpaged())) + .isEmpty(); + + Character legacy = characterRepository.findById(legacyCharacterId).orElseThrow(); + assertThat(legacy.getName()).isEqualTo("Legacy Actor"); + assertThat(characterRepository.findWithInventoryById(legacyCharacterId)).isPresent(); + assertThat(characterRepository.findByIdAndTenantId(legacyCharacterId, entityTenantRowId)) + .isPresent(); + assertThat( + characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( + entityTenantRowId, 23L, "shared-live", Pageable.unpaged())) + .hasSize(1); + assertThat( + inventoryEntryRepository.findByIdCharacterIdAndCharacterTenantId( + legacyCharacterId, entityTenantRowId, Pageable.unpaged())) + .hasSize(1); + assertThat( + characterEquipmentRepository.findByIdCharacterIdAndCharacterTenantId( + legacyCharacterId, entityTenantRowId, Pageable.unpaged())) + .hasSize(1); + legacy.setName("Updated Legacy Actor"); + assertThat(characterRepository.save(legacy).getName()).isEqualTo("Updated Legacy Actor"); + + CharacterFriendKey legacyFriendKey = new CharacterFriendKey(); + legacyFriendKey.setCharacterId(legacyCharacterId); + legacyFriendKey.setFriendId(legacyFriendId); + CharacterFriendKey canonicalFriendKey = new CharacterFriendKey(); + canonicalFriendKey.setCharacterId(canonicalCharacterId); + canonicalFriendKey.setFriendId(legacyFriendId); + CharacterFriendKey canonicalTargetKey = new CharacterFriendKey(); + canonicalTargetKey.setCharacterId(legacyCharacterId); + canonicalTargetKey.setFriendId(canonicalCharacterId); + assertThat(characterFriendRepository.countByTenantId(entityTenantRowId)).isEqualTo(1); + assertThat(characterFriendRepository.findByIdCharacterId(legacyCharacterId, Pageable.unpaged())) + .hasSize(1); + assertThat(characterFriendRepository.findById(legacyFriendKey)).isPresent(); + assertThat(characterFriendRepository.findById(canonicalFriendKey)).isEmpty(); + assertThat(characterFriendRepository.findById(canonicalTargetKey)).isEmpty(); + CharacterFriend forbiddenFriend = new CharacterFriend(); + forbiddenFriend.setId(canonicalFriendKey); + forbiddenFriend.setTenantId(entityTenantRowId); + forbiddenFriend.setCreatedAt(Instant.now()); + assertThatThrownBy(() -> characterFriendRepository.save(forbiddenFriend)) + .isInstanceOf(IllegalStateException.class); + forbiddenFriend.setId(canonicalTargetKey); + assertThatThrownBy(() -> characterFriendRepository.save(forbiddenFriend)) + .isInstanceOf(IllegalStateException.class); + characterFriendRepository.deleteById(canonicalFriendKey); + characterFriendRepository.deleteById(canonicalTargetKey); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM character_friend WHERE character_id = ? OR friend_id = ?", + Integer.class, + canonicalCharacterId, + canonicalCharacterId)) + .isEqualTo(2); + characterFriendRepository.deleteById(legacyFriendKey); + assertThat(characterFriendRepository.countByTenantId(entityTenantRowId)).isZero(); + CharacterFriend restoredLegacyFriend = new CharacterFriend(); + restoredLegacyFriend.setId(legacyFriendKey); + restoredLegacyFriend.setTenantId(entityTenantRowId); + restoredLegacyFriend.setCreatedAt(Instant.now()); + assertThat(characterFriendRepository.save(restoredLegacyFriend)).isNotNull(); + + assertThat( + actorResourceStateRepository + .findByTenantIdAndPlayableStateKeyAndCharacterIdOrderByStatKeyAsc( + entityTenantRowId, namespaceUuid.toString(), canonicalCharacterId)) + .isEmpty(); + ActorResourceState legacyResource = + actorResourceStateRepository + .findByTenantIdAndPlayableStateKeyAndCharacterIdOrderByStatKeyAsc( + entityTenantRowId, "shared-live", legacyCharacterId) + .getFirst(); + legacyResource.setCurrentValue(8L); + actorResourceStateRepository.save(legacyResource); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE id = ?", + Long.class, + legacyResourceId)) + .isEqualTo(8L); + ActorResourceState canonicalResourceWrite = new ActorResourceState(); + canonicalResourceWrite.setId(canonicalResourceId); + canonicalResourceWrite.setCharacterId(legacyCharacterId); + canonicalResourceWrite.setCurrentValue(99L); + assertThatThrownBy(() -> actorResourceStateRepository.save(canonicalResourceWrite)) + .isInstanceOf(IllegalStateException.class); + ActorResourceState addedLegacyResource = new ActorResourceState(); + addedLegacyResource.setTenantId(entityTenantRowId); + addedLegacyResource.setPlayableStateKey("shared-live"); + addedLegacyResource.setCharacterId(legacyCharacterId); + addedLegacyResource.setStatKey("new-focus"); + addedLegacyResource.setCurrentValue(11L); + Long addedLegacyResourceId = actorResourceStateRepository.save(addedLegacyResource).getId(); + assertThat(addedLegacyResourceId).isNotNull(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE id = ?", + Long.class, + addedLegacyResourceId)) + .isEqualTo(11L); + canonicalResourceWrite.setId(null); + canonicalResourceWrite.setTenantId(entityTenantRowId); + canonicalResourceWrite.setCharacterId(canonicalCharacterId); + canonicalResourceWrite.setPlayableStateKey(namespaceUuid.toString()); + canonicalResourceWrite.setStatKey("new-focus"); + assertThatThrownBy(() -> actorResourceStateRepository.save(canonicalResourceWrite)) + .isInstanceOf(IllegalStateException.class); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE id = ?", + Long.class, + canonicalResourceId)) + .isEqualTo(5L); + + Instant beforeExpiry = Instant.parse("2026-01-01T00:00:00Z"); + assertThat( + actorActiveConditionRepository.findActiveForCharacter( + entityTenantRowId, namespaceUuid.toString(), canonicalCharacterId, beforeExpiry)) + .isEmpty(); + assertThat( + actorActiveConditionRepository + .findFirstByTenantIdAndPlayableStateKeyAndCharacterIdAndSourceTypeAndSourceIdOrderByIdAsc( + entityTenantRowId, + namespaceUuid.toString(), + canonicalCharacterId, + "fixture", + "canonical")) + .isEmpty(); + ActorActiveCondition legacyCondition = + actorActiveConditionRepository + .findActiveForCharacter( + entityTenantRowId, "shared-live", legacyCharacterId, beforeExpiry) + .getFirst(); + legacyCondition.setStackCount(2); + actorActiveConditionRepository.save(legacyCondition); + assertThat( + jdbcTemplate.queryForObject( + "SELECT stack_count FROM actor_active_conditions WHERE id = ?", + Integer.class, + legacyConditionId)) + .isEqualTo(2); + ActorActiveCondition canonicalConditionWrite = new ActorActiveCondition(); + canonicalConditionWrite.setId(canonicalConditionId); + canonicalConditionWrite.setCharacterId(legacyCharacterId); + canonicalConditionWrite.setStackCount(9); + assertThatThrownBy(() -> actorActiveConditionRepository.save(canonicalConditionWrite)) + .isInstanceOf(IllegalStateException.class); + ActorActiveCondition addedLegacyCondition = new ActorActiveCondition(); + addedLegacyCondition.setTenantId(entityTenantRowId); + addedLegacyCondition.setPlayableStateKey("shared-live"); + addedLegacyCondition.setCharacterId(legacyCharacterId); + addedLegacyCondition.setConditionKey("new-shield"); + addedLegacyCondition.setSourceType("fixture"); + addedLegacyCondition.setSourceId("new-legacy"); + addedLegacyCondition.setExpiresAt(expiry.plusSeconds(60)); + Long addedLegacyConditionId = actorActiveConditionRepository.save(addedLegacyCondition).getId(); + assertThat(addedLegacyConditionId).isNotNull(); + assertThat( + actorActiveConditionRepository + .findFirstByTenantIdAndPlayableStateKeyAndCharacterIdAndSourceTypeAndSourceIdOrderByIdAsc( + entityTenantRowId, "shared-live", legacyCharacterId, "fixture", "new-legacy")) + .isPresent(); + canonicalConditionWrite.setId(null); + canonicalConditionWrite.setTenantId(entityTenantRowId); + canonicalConditionWrite.setCharacterId(canonicalCharacterId); + canonicalConditionWrite.setPlayableStateKey(namespaceUuid.toString()); + canonicalConditionWrite.setConditionKey("new-shield"); + canonicalConditionWrite.setSourceType("fixture"); + assertThatThrownBy(() -> actorActiveConditionRepository.save(canonicalConditionWrite)) + .isInstanceOf(IllegalStateException.class); + assertThat(actorActiveConditionRepository.deleteExpired(expiry.plusSeconds(1))).isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM actor_active_conditions WHERE id = ?", + Integer.class, + addedLegacyConditionId)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM actor_active_conditions WHERE id = ?", + Integer.class, + canonicalConditionId)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM actor_active_conditions WHERE id = ?", + Integer.class, + legacyConditionId)) + .isZero(); + + Character canonicalIdWrite = new Character(); + canonicalIdWrite.setId(canonicalCharacterId); + canonicalIdWrite.setTenantId(entityTenantRowId); + canonicalIdWrite.setAccountId(23L); + canonicalIdWrite.setPlayableStateKey(namespaceUuid.toString()); + canonicalIdWrite.setName("Changed Canonical Actor"); + assertThatThrownBy(() -> characterRepository.save(canonicalIdWrite)) + .isInstanceOf(java.util.NoSuchElementException.class); + assertThat( + jdbcTemplate.queryForObject( + "SELECT name FROM characters WHERE id = ?", String.class, canonicalCharacterId)) + .isEqualTo("Canonical Actor"); + + PreseededActorAssignmentOwnerEvidence owner = + evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + assignmentRequest(owner).expectedTarget()))) + .isPresent(); + CanonicalGameplayRosterTarget rosterTarget = + new CanonicalGameplayRosterTarget( + tenantUuid, + realmUuid, + "world", + "realm", + UUID.randomUUID(), + 4L, + 1L, + 1L, + owner.canonicalVersionUuid(), + owner.frozenPolicyDigest(), + owner.publishedReleaseBundleRef(), + "5".repeat(64), + owner.publishedOwnerProofDigest(), + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + UUID rosterRequestUuid = UUID.randomUUID(); + CanonicalGameplayRosterReadRequest rosterRequest = + new CanonicalGameplayRosterReadRequest( + rosterRequestUuid, + accountUuid, + rosterTarget, + new CanonicalGameplayRosterExecutionContext( + accountUuid, + tenantUuid, + namespaceUuid, + rosterTarget.gameInstanceUuid(), + null, + UUID.randomUUID(), + realmUuid, + rosterRequestUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + assertThat( + characterRepository + .captureCanonicalGameplayRosterSnapshot( + rosterRequest, + new CanonicalGameplayRosterOwnerEvidence( + rosterRequestUuid, accountUuid, rosterTarget, Instant.now())) + .actors()) + .extracting(actor -> actor.characterUuid()) + .containsExactly(assigned.characterUuid()); + } + @Test void selectedAssignmentReadRequiresExactOwnerTargetAndCurrentActorProvenance() { PreseededActorAssignmentResult assigned = 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 a3800911d8..142a3d42a4 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 @@ -14,6 +14,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.repository.ActorIdentityRepository; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -72,6 +73,7 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private CharacterRepository characterRepository; + @Autowired private ActorIdentityRepository actorIdentityRepository; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private Flyway flyway; @@ -206,14 +208,23 @@ void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .isEmpty(); - Character resolved = characterRepository.findById(resolvedId).orElseThrow(); - assertThat(resolved.getActorIdentity().characterUuid()).isEqualTo(resolvedActorUuid); - assertThat(resolved.getActorIdentity().accountUuid()).isEqualTo(accountUuid); - assertThat(resolved.getActorIdentity().tenantUuid()).isEqualTo(tenantUuid); - assertThat(resolved.getActorIdentity().playableStateNamespaceId()).isEqualTo(namespaceUuid); - assertThat(resolved.getActorIdentity().playableStateScope()) + assertThat(characterRepository.findById(resolvedId)).isEmpty(); + var resolved = + actorIdentityRepository + .findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + resolvedActorUuid.toString()) + .orElseThrow(); + assertThat(resolved.characterUuid()).isEqualTo(resolvedActorUuid); + assertThat(resolved.accountUuid()).isEqualTo(accountUuid); + assertThat(resolved.tenantUuid()).isEqualTo(tenantUuid); + assertThat(resolved.playableStateNamespaceId()).isEqualTo(namespaceUuid); + assertThat(resolved.playableStateScope()) .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - assertThat(resolved.getActorIdentity().status().name()).isEqualTo("OWNER_RESOLVED"); + assertThat(resolved.status().name()).isEqualTo("OWNER_RESOLVED"); assertThat( characterRepository.findById(legacyId).orElseThrow().getActorIdentity().status().name()) .isEqualTo("QUARANTINED"); From d7f78ebbb5e2d13bfd73885202c0742c41e3f94b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:00:46 +1300 Subject: [PATCH 14/28] Reject unsettled admission holds and qualify passive roster contracts --- .../entity-management-service/README.md | 2 +- .../api-contracts.md | 2 +- .../runtime-and-data.md | 1 + .../gameplay-rules-entities-and-effects.md | 4 +- .../player-access-and-session.md | 2 + dev-tools/validation/check-flyway-versions.py | 23 ++ ...ginal_start_session_source_protections.sql | 267 +++++++++--------- ...sionProtectionPostgresIntegrationTest.java | 175 +++++++++++- 8 files changed, 333 insertions(+), 143 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index def19fe327..446abd5e8e 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Entity V1003–V1010 prepares opaque actor UUIDs, quarantine metadata, namespace/scope integrity, and assignment/receipt/roster storage while retaining legacy values. Manually composed source services and exact canonical repository readers are present without Spring registration, authenticated clients, or gRPC handlers. Existing legacy reads, roster listing, updates, cache access, scoped consumers, condition expiry, and cleanup retain develop behavior; this preparation does not enforce runtime quarantine or replace gameplay admission. Authenticated owner provenance, the real Game Session caller and execution replacement, and production activation remain unproved. Focused storage and unchanged legacy player-flow qualification is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); [Entity API Contracts](./api-contracts.md#implementation-status) owns the detailed source and wire contract. +Entity V1003–V1010 prepares opaque actor UUIDs, quarantine metadata, namespace/scope integrity, and assignment/receipt/roster storage while retaining legacy values. Exact canonical repository readers, including `ActorIdentityRepository` and `CharacterRepository`, are registered Spring beans. The assignment, receipt, and roster service compositions remain manually composed and unregistered, with no authenticated clients or gRPC handlers. Existing legacy reads, roster listing, updates, cache access, scoped consumers, condition expiry, and cleanup retain develop behavior; this preparation does not enforce runtime quarantine or replace gameplay admission. Authenticated owner provenance, the real Game Session caller and execution replacement, and production activation remain unproved. Focused storage and unchanged legacy player-flow qualification is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); [Entity API Contracts](./api-contracts.md#implementation-status) owns the detailed source and wire contract. 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. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 676d01b804..8d5e80bed4 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -10,7 +10,7 @@ Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/ The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. +The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. At the canonical roster bridge, the owner supplies `game_instance_uuid` as already canonical, non-nil UUID text under the shared [Identifier Format Conventions](../../system-architecture-identifier-glossary.md#identifier-format-conventions). That boundary contract does not change the generic assignment digest path: it hashes the exact opaque owner-supplied text and does not infer aliases, parse, or normalize it. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. 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 5047468f68..d4105eb90e 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -23,6 +23,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude new `OWNER_RESOLVED` actors, including updates and condition expiry. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The source services are manually composed and unregistered; no authenticated transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). +- Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. Before any handler, service, or alternative snapshot writer is registered, this family must have an ADR 0163 retention declaration covering its class, terminal and reference blockers, compatible horizon, holds, metrics, cleanup cadence, and proved owner-local disposal. This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. 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 5f99b982fe..b00ea9eb2e 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 @@ -113,11 +113,11 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof -- Current passive preparation at `79fac839c5086571439e6e5e219eb58f2fa4f47f` on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c`: Entity executed 234 unit cases in the first recut run and 24 physical PostgreSQL integration cases in the final run, all with zero failures, errors or skips; units were up-to-date in the final run. Default combined V1/Saga1000–1002/Entity1003–1010 fresh history and actual-parent retained-data upgrades passed, preserving installed ranks, scripts, checksums and success. Account's 15 new protection cases also passed locally; its broader local 236-case integration run had two unavailable endpoint fixtures (PostgreSQL refusal and Redis host-port timeout), so that full local gate failed. The identical Account/Common/proto/build input scope at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` passed source Validation Account job 115335024215: 1295 unit cases with four existing filesystem skips, and 240 integration cases with zero failures/errors/skips, including both unavailable local suites. Main verified its own Account artifact 11822625688 and matching inputs. Affected formatting, Checkstyle, SpotBugs and documentation checks pass; the final Account integration static/documentation gate passed in 28s. The source-built, run-owned fresh-bootstrap proof rebuilt jars/images and passed WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK after the configuration-only discovery correction and isolated native Docker client recovery. These positive baseline results preserve legacy behavior; authenticated canonical owner/caller/controller/execution replacement and production activation remain unproved. The complete donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` retains later runtime obligations. Current published-head CI/reviews remain separate; no GDS semantic or ordering closure is claimed. +- Historical passive-preparation baseline at `79fac839c5086571439e6e5e219eb58f2fa4f47f` on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c`: Entity executed 234 unit cases in the first recut run and 24 physical PostgreSQL integration cases in the final run, all with zero failures, errors or skips; units were up-to-date in the final run. Default combined V1/Saga1000–1002/Entity1003–1010 fresh history and actual-parent retained-data upgrades passed, preserving installed ranks, scripts, checksums and success. Account's 15 focused protection cases passed locally; its broader local 236-case integration run had two unavailable endpoint fixtures (PostgreSQL refusal and Redis host-port timeout), so that full local gate failed. The identical Account/Common/proto/build input scope at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` passed source Validation Account job 115335024215: 1,295 unit cases with four existing filesystem skips, and 240 integration cases with zero failures, errors or skips, including both unavailable local suites. Main verified its own Account artifact 11822625688 and matching inputs. Affected formatting, Checkstyle, SpotBugs and documentation checks passed; the final Account integration static/documentation gate passed in 28s. These Account results are historical and their detailed owner attribution is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). The source-built, run-owned fresh-bootstrap proof rebuilt jars/images and passed WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK after the configuration-only discovery correction and isolated native Docker client recovery. These baseline results preserve legacy behavior; authenticated canonical owner/caller/controller/execution replacement and production activation remain unproved. The complete donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` retains later runtime obligations. Current published-head CI/reviews remain separate; no GDS semantic or ordering closure is claimed. - Subsequent review corrections on develop `18f8063306c2ddb4337646de50b73619915a0e25` pass the full Entity gate: 236 unit cases executed in the first correction run and 26 physical PostgreSQL cases executed in the final gate, with zero failures, errors or skips. The new PostgreSQL proof checks Spring-proxy rejection without a caller-owned writable transaction and overlapping roster reads while preserving assignment writer exclusion. Both assignment digest paths use the same ordered encoder with literal `SHARED`/`ISOLATED` digest vectors, and run-owned capabilities admit release references through the documented 1,024-character bound. The canonical 79-leaf implementation-tracker check passes with actual migration file anchors. Account correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). These are bounded passive storage/source corrections; canonical runtime consumers and genuine owner admission remain open. -- The final legacy-bridge isolation correction passes the full Entity gate with 237 unit and 27 physical PostgreSQL integration cases, zero failures, errors or skips. The colliding numeric-tenant fixture proves that canonical actors and their inventory, equipment, friend, resource and condition rows are hidden from legacy readers, guarded writes reject canonical stored parents even when a legacy parent is supplied, and expiry preserves canonical conditions. Ordinary legacy reads, inserts, updates, deletes and expiry remain usable; exact canonical UUID, receipt and roster reads remain usable. The inventory-bearing positive case also exposed and corrected a missing inventory-version projection. A fresh, uncached TCP proto-generation and Java-compilation proof passes; the earlier source Runtime compiler failure remains unreproduced and does not supply current packaged runtime proof. New published-head CI and the remaining allocated Hosted checkpoint remain required. +- Current passive-preparation proof is the final legacy-bridge isolation correction: the full Entity gate passed with 237 unit and 27 physical PostgreSQL integration cases, zero failures, errors or skips. Account's latest 20-case correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). The colliding numeric-tenant fixture proves that canonical actors and their inventory, equipment, friend, resource and condition rows are hidden from legacy readers, guarded writes reject canonical stored parents even when a legacy parent is supplied, and expiry preserves canonical conditions. Ordinary legacy reads, inserts, updates, deletes and expiry remain usable; exact canonical UUID, receipt and roster reads remain usable. The inventory-bearing positive case also exposed and corrected a missing inventory-version projection. A fresh, uncached TCP proto-generation and Java-compilation proof passes; the earlier source Runtime compiler failure remains unreproduced and does not supply current packaged runtime proof. The final allocated Hosted review is complete; its corrections require qualification and new published-head CI. - Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is 1005 with no out-of-order migrations. The 211 unit cases retain the preceding executed-run attribution and were up-to-date in the final 50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. 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 fe2b426ce2..8d3647ff48 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,8 @@ The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca1 The subsequent Hosted/CLI correction on develop `18f8063306c2ddb4337646de50b73619915a0e25` executed 18 focused Account PostgreSQL cases with zero failures, errors or skips. Acquisition now rejects admission data that cannot satisfy immutable settlement bounds; committed activation fixtures run the acquisition, source-child and deferred-completeness guards. The proof includes the 256-source boundary, canonical Base64 and UTF-16 ordering, a complete activation tuple above 135,168 bytes, and settlement after lease expiry. Actual jOOQ generation, compilation, integration Checkstyle and SpotBugs, formatting and documentation checks passed. This corrects the bounded fixture proof; the older broad source-CI counts remain historical and do not qualify the changed SQL or establish genuine owner production. +The latest local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. + ### Entity character-creation denial The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 4f1ab5f92a..0b0f2629f9 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -164,6 +164,15 @@ def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str issues.append(f"services/{project}: new migration {item.path} (V{item.version_text}) " f"must exceed effective parent frontier V{version_label(frontier)}") + # A shared migration remains in the raw repository even if a project stops + # loading it. Compare each project's effective history so removing either + # the runtime dependency or a Flyway location cannot silently drop it. + for project, previous in sorted(parent_grouped.items()): + current_paths = {item.path for item in grouped.get(project, [])} + for item in previous: + if item.path not in current_paths: + issues.append(f"services/{project}: historical effective migration no longer applied: {item.path}") + # Treat parent histories conservatively as applied; never rewrite their names/checksums. for item in parent_migrations: if item.path not in current: @@ -217,11 +226,25 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str check("composed runtime convention", {**composed, local + "V2__new.sql": b"-- new"}, composed, "frontier V1002") test_only = {**history, "services/example-service/build.gradle.kts": b'testImplementation(project(":common-saga"))'} check("test-only dependency", {**test_only, local + "V2__new.sql": b"-- new"}, test_only, None) + dependency_removed = {**history, "services/example-service/build.gradle.kts": b"dependencies {}"} + check("removed runtime dependency", dependency_removed, history, "historical effective migration no longer applied") + explicit_saga_location = {**history, "services/example-service/src/main/resources/application.yml": + b"spring:\n flyway:\n locations: classpath:db/migration/saga\n"} + location_removed = {**explicit_saga_location, "services/example-service/src/main/resources/application.yml": + b"spring:\n flyway:\n locations: classpath:db/migration/other\n"} + check("removed Flyway location", location_removed, explicit_saga_location, + "historical effective migration no longer applied") second_local = "services/second-service/src/main/resources/db/migration/" multiple = {**history, "services/second-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], "services/second-service/src/main/resources/application.yml": wiring["services/example-service/src/main/resources/application.yml"], second_local + "V2000__later.sql": b"-- later"} check("every adopter frontier", {**multiple, shared + "V1003__new.sql": b"-- new"}, multiple, "frontier V2000") + one_adopter_removed = {**multiple, "services/example-service/build.gradle.kts": b"dependencies {}"} + membership_issues, _, _ = collect_issues(one_adopter_removed, multiple) + if (not any("services/example-service: historical effective migration no longer applied" in issue + for issue in membership_issues) + or any("services/second-service:" in issue for issue in membership_issues)): + raise AssertionError(f"one adopter removal affected the wrong project histories: {membership_issues}") with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) diff --git a/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql index ae48d7bb70..3c33b4a44c 100644 --- a/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql +++ b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql @@ -79,6 +79,133 @@ BEGIN END; $$; +-- Acquisition and settlement require the same exact World hold before a source +-- protection can become pending. Return the only valid committed next pointer. +CREATE FUNCTION account_ss_admission_canonical_hold_next_pointer( + original account_start_session_admission_protections +) RETURNS NUMERIC LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + hold_json JSONB; + hold_request_json JSONB; + canonical_hold TEXT; + canonical_hold_request TEXT; + prior_pointer NUMERIC; +BEGIN + hold_json := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(hold_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_json)) <> 5 + OR NOT (hold_json ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR hold_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is malformed' + USING ERRCODE = '23514'; + END IF; + IF (hold_json->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_json->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_json->>'holdId' IS DISTINCT FROM (hold_json->>'holdId')::UUID::TEXT + OR hold_json->>'holdFence' IS DISTINCT FROM (hold_json->>'holdFence')::UUID::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is nil' + USING ERRCODE = '23514'; + END IF; + hold_request_json := convert_from(decode(hold_json->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF regexp_replace(encode(decode(hold_json->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM hold_json->>'requestBytesBase64' + OR hold_json->>'holdBindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(decode(hold_json->>'requestBytesBase64', 'base64')), 'hex') + OR jsonb_typeof(hold_request_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json)) <> 2 + OR NOT (hold_request_json ?& ARRAY['schema', 'request']) + OR hold_request_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json->'request')) <> 14 + OR NOT (hold_request_json->'request' ?& ARRAY[ + 'activeLifecycleEpoch', 'canonicalGameInstanceId', 'canonicalTenantId', + 'canonicalVersionId', 'expectedCatalogRevision', 'expectedPriorPointerVersion', + 'initialAdmissionOrigin', 'initialAdmissionRequestDigest', + 'initialAdmissionRequestId', 'playableStateNamespaceId', 'playableStateScope', + 'realmId', 'targetNamespace', 'worldSlug']) + OR hold_request_json->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request_json->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request_json->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold request differs from retained protection' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM jsonb_each(hold_request_json->'request') field + WHERE field.key <> 'expectedPriorPointerVersion' + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') NOT IN ('string', 'null') THEN + RAISE EXCEPTION 'Original StartSession hold request fields have invalid JSON types' + USING ERRCODE = '23514'; + END IF; + canonical_hold_request := '{"request":{"activeLifecycleEpoch":' + || to_json(hold_request_json->'request'->>'activeLifecycleEpoch')::TEXT + || ',"canonicalGameInstanceId":' + || to_json(hold_request_json->'request'->>'canonicalGameInstanceId')::TEXT + || ',"canonicalTenantId":' + || to_json(hold_request_json->'request'->>'canonicalTenantId')::TEXT + || ',"canonicalVersionId":' + || to_json(hold_request_json->'request'->>'canonicalVersionId')::TEXT + || ',"expectedCatalogRevision":' + || to_json(hold_request_json->'request'->>'expectedCatalogRevision')::TEXT + || ',"expectedPriorPointerVersion":' + || CASE + WHEN jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'null' + THEN 'null' + ELSE to_json(hold_request_json->'request'->>'expectedPriorPointerVersion')::TEXT + END + || ',"initialAdmissionOrigin":' + || to_json(hold_request_json->'request'->>'initialAdmissionOrigin')::TEXT + || ',"initialAdmissionRequestDigest":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestDigest')::TEXT + || ',"initialAdmissionRequestId":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestId')::TEXT + || ',"playableStateNamespaceId":' + || to_json(hold_request_json->'request'->>'playableStateNamespaceId')::TEXT + || ',"playableStateScope":' + || to_json(hold_request_json->'request'->>'playableStateScope')::TEXT + || ',"realmId":' + || to_json(hold_request_json->'request'->>'realmId')::TEXT + || ',"targetNamespace":' + || to_json(hold_request_json->'request'->>'targetNamespace')::TEXT + || ',"worldSlug":' + || to_json(hold_request_json->'request'->>'worldSlug')::TEXT + || '},"schema":"world-canonical-initial-admission-hold-request/v1"}'; + IF convert_to(canonical_hold_request, 'UTF8') IS DISTINCT FROM + decode(hold_json->>'requestBytesBase64', 'base64') THEN + RAISE EXCEPTION 'Original StartSession hold request is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + canonical_hold := '{"holdBindingDigest":"' || (hold_json->>'holdBindingDigest') + || '","holdFence":"' || (hold_json->>'holdFence') + || '","holdId":"' || (hold_json->>'holdId') + || '","requestBytesBase64":"' || (hold_json->>'requestBytesBase64') + || '","schema":"world-canonical-initial-admission-hold-identity/v1"}'; + IF convert_to(canonical_hold, 'UTF8') IS DISTINCT FROM original.world_admission_hold_identity_bytes THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is not canonical' + USING ERRCODE = '23514'; + END IF; + + IF hold_request_json->'request'->>'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND hold_request_json->'request'->'expectedPriorPointerVersion' = 'null'::JSONB THEN + RETURN 1; + ELSIF hold_request_json->'request'->>'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'string' + AND hold_request_json->'request'->>'expectedPriorPointerVersion' ~ '^[1-9][0-9]{0,18}$' THEN + prior_pointer := (hold_request_json->'request'->>'expectedPriorPointerVersion')::NUMERIC; + IF prior_pointer >= 9223372036854775807 THEN + RAISE EXCEPTION 'Original StartSession pointer version cannot advance without overflow' + USING ERRCODE = '23514'; + END IF; + RETURN prior_pointer + 1; + ELSE + RAISE EXCEPTION 'Original StartSession hold has an invalid pointer precondition' + USING ERRCODE = '23514'; + END IF; +END; +$$; + -- Account currentness must independently reconstruct the exact live original actor, -- registry, signer and source capture before invoking this integrity boundary. SQL -- validates retained bindings; neither a capture nor a historical observation grants @@ -95,8 +222,6 @@ DECLARE snapshot_value JSONB; tuple_value JSONB; request_value JSONB; - hold_value JSONB; - hold_request JSONB; projection_value JSONB; source_value JSONB; source_bytes BYTEA; @@ -245,22 +370,7 @@ BEGIN USING ERRCODE = '23514'; END IF; - hold_value := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; - hold_request := convert_from(decode(hold_value->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; - IF hold_value->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' - OR (SELECT count(*) FROM jsonb_object_keys(hold_value)) <> 5 - OR NOT (hold_value ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) - OR EXISTS (SELECT 1 FROM jsonb_each(hold_value) field WHERE jsonb_typeof(field.value) <> 'string') - OR (hold_value->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID - OR (hold_value->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID - OR hold_value->>'requestBytesBase64' IS DISTINCT FROM regexp_replace(encode(decode(hold_value->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') - OR hold_value->>'holdBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') - OR hold_request->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' - OR hold_request->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace - OR hold_request->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT - OR hold_request->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN - RAISE EXCEPTION 'Admission hold identity differs from original instance and request' USING ERRCODE = '23514'; - END IF; + PERFORM account_ss_admission_canonical_hold_next_pointer(original); -- Original World source children remain immutable even when World has settled. PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); IF require_complete THEN @@ -433,16 +543,12 @@ DECLARE existing account_start_session_admission_protection_settlements%ROWTYPE; terminal_json JSONB; evidence_json JSONB; - hold_json JSONB; - hold_request_json JSONB; snapshot_json JSONB; evidence_bytes BYTEA; owner_proof_bytes BYTEA; canonical_outer TEXT; canonical_evidence TEXT; canonical_request TEXT; - canonical_hold TEXT; - canonical_hold_request TEXT; source_vector TEXT; source_count BIGINT; source_bytes_total BIGINT; @@ -469,8 +575,6 @@ DECLARE terminal_at_text TEXT; terminal_stem TEXT; expected_pointer NUMERIC; - prior_pointer NUMERIC; - original_request JSONB; BEGIN SELECT * INTO STRICT original FROM account_start_session_admission_protections @@ -636,103 +740,7 @@ BEGIN USING ERRCODE = '23514'; END IF; - -- Validate the exact retained World hold identity and request, including the original - -- target and the pointer precondition used to derive a committed next pointer. - hold_json := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; - IF jsonb_typeof(hold_json) IS DISTINCT FROM 'object' - OR (SELECT count(*) FROM jsonb_object_keys(hold_json)) <> 5 - OR NOT (hold_json ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) - OR EXISTS (SELECT 1 FROM jsonb_each(hold_json) field - WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') - OR hold_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' THEN - RAISE EXCEPTION 'Original StartSession admission hold identity is malformed' - USING ERRCODE = '23514'; - END IF; - IF (hold_json->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID - OR (hold_json->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID - OR hold_json->>'holdId' IS DISTINCT FROM (hold_json->>'holdId')::UUID::TEXT - OR hold_json->>'holdFence' IS DISTINCT FROM (hold_json->>'holdFence')::UUID::TEXT THEN - RAISE EXCEPTION 'Original StartSession admission hold identity is nil' - USING ERRCODE = '23514'; - END IF; - hold_request_json := convert_from(decode(hold_json->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; - IF regexp_replace(encode(decode(hold_json->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') - IS DISTINCT FROM hold_json->>'requestBytesBase64' - OR hold_json->>'holdBindingDigest' IS DISTINCT FROM - 'sha256:' || encode(sha256(decode(hold_json->>'requestBytesBase64', 'base64')), 'hex') - OR jsonb_typeof(hold_request_json) IS DISTINCT FROM 'object' - OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json)) <> 2 - OR NOT (hold_request_json ?& ARRAY['schema', 'request']) - OR hold_request_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' - OR jsonb_typeof(hold_request_json->'request') IS DISTINCT FROM 'object' - OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json->'request')) <> 14 - OR NOT (hold_request_json->'request' ?& ARRAY[ - 'activeLifecycleEpoch', 'canonicalGameInstanceId', 'canonicalTenantId', - 'canonicalVersionId', 'expectedCatalogRevision', 'expectedPriorPointerVersion', - 'initialAdmissionOrigin', 'initialAdmissionRequestDigest', - 'initialAdmissionRequestId', 'playableStateNamespaceId', 'playableStateScope', - 'realmId', 'targetNamespace', 'worldSlug']) - OR hold_request_json->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace - OR hold_request_json->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT - OR hold_request_json->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN - RAISE EXCEPTION 'Original StartSession admission hold request differs from retained protection' - USING ERRCODE = '23514'; - END IF; - IF EXISTS ( - SELECT 1 FROM jsonb_each(hold_request_json->'request') field - WHERE field.key <> 'expectedPriorPointerVersion' - AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') - OR jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') NOT IN ('string', 'null') THEN - RAISE EXCEPTION 'Original StartSession hold request fields have invalid JSON types' - USING ERRCODE = '23514'; - END IF; - canonical_hold_request := '{"request":{"activeLifecycleEpoch":' - || to_json(hold_request_json->'request'->>'activeLifecycleEpoch')::TEXT - || ',"canonicalGameInstanceId":' - || to_json(hold_request_json->'request'->>'canonicalGameInstanceId')::TEXT - || ',"canonicalTenantId":' - || to_json(hold_request_json->'request'->>'canonicalTenantId')::TEXT - || ',"canonicalVersionId":' - || to_json(hold_request_json->'request'->>'canonicalVersionId')::TEXT - || ',"expectedCatalogRevision":' - || to_json(hold_request_json->'request'->>'expectedCatalogRevision')::TEXT - || ',"expectedPriorPointerVersion":' - || CASE - WHEN jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'null' - THEN 'null' - ELSE to_json(hold_request_json->'request'->>'expectedPriorPointerVersion')::TEXT - END - || ',"initialAdmissionOrigin":' - || to_json(hold_request_json->'request'->>'initialAdmissionOrigin')::TEXT - || ',"initialAdmissionRequestDigest":' - || to_json(hold_request_json->'request'->>'initialAdmissionRequestDigest')::TEXT - || ',"initialAdmissionRequestId":' - || to_json(hold_request_json->'request'->>'initialAdmissionRequestId')::TEXT - || ',"playableStateNamespaceId":' - || to_json(hold_request_json->'request'->>'playableStateNamespaceId')::TEXT - || ',"playableStateScope":' - || to_json(hold_request_json->'request'->>'playableStateScope')::TEXT - || ',"realmId":' - || to_json(hold_request_json->'request'->>'realmId')::TEXT - || ',"targetNamespace":' - || to_json(hold_request_json->'request'->>'targetNamespace')::TEXT - || ',"worldSlug":' - || to_json(hold_request_json->'request'->>'worldSlug')::TEXT - || '},"schema":"world-canonical-initial-admission-hold-request/v1"}'; - IF convert_to(canonical_hold_request, 'UTF8') IS DISTINCT FROM - decode(hold_json->>'requestBytesBase64', 'base64') THEN - RAISE EXCEPTION 'Original StartSession hold request is not canonical JSON' - USING ERRCODE = '23514'; - END IF; - canonical_hold := '{"holdBindingDigest":"' || (hold_json->>'holdBindingDigest') - || '","holdFence":"' || (hold_json->>'holdFence') - || '","holdId":"' || (hold_json->>'holdId') - || '","requestBytesBase64":"' || (hold_json->>'requestBytesBase64') - || '","schema":"world-canonical-initial-admission-hold-identity/v1"}'; - IF convert_to(canonical_hold, 'UTF8') IS DISTINCT FROM original.world_admission_hold_identity_bytes THEN - RAISE EXCEPTION 'Original StartSession admission hold identity is not canonical' - USING ERRCODE = '23514'; - END IF; + expected_pointer := account_ss_admission_canonical_hold_next_pointer(original); -- The actual Game Session codec frames the hold and seven terminal fields. Do not treat -- its opaque terminal proof digest as permission; only the exact COMMITTED/ABORTED shape @@ -824,7 +832,6 @@ BEGIN RAISE EXCEPTION 'Original StartSession owner proof timestamp stem is not normalized' USING ERRCODE = '23514'; END IF; - original_request := hold_request_json->'request'; IF proof_outcome = 'COMMITTED' THEN IF pointer_marker IS DISTINCT FROM 'PRESENT' OR pointer_text IS NULL OR pointer_text !~ '^[1-9][0-9]{0,18}$' @@ -834,22 +841,6 @@ BEGIN RAISE EXCEPTION 'Committed Game Session terminal proof has invalid outcome fields' USING ERRCODE = '23514'; END IF; - IF original_request->>'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' - AND original_request->'expectedPriorPointerVersion' = 'null'::JSONB THEN - expected_pointer := 1; - ELSIF original_request->>'initialAdmissionOrigin' = 'EXPECT_CLOSED' - AND jsonb_typeof(original_request->'expectedPriorPointerVersion') = 'string' - AND original_request->>'expectedPriorPointerVersion' ~ '^[1-9][0-9]{0,18}$' THEN - prior_pointer := (original_request->>'expectedPriorPointerVersion')::NUMERIC; - IF prior_pointer >= 9223372036854775807 THEN - RAISE EXCEPTION 'Original StartSession pointer version cannot advance without overflow' - USING ERRCODE = '23514'; - END IF; - expected_pointer := prior_pointer + 1; - ELSE - RAISE EXCEPTION 'Original StartSession hold has an invalid pointer precondition' - USING ERRCODE = '23514'; - END IF; IF pointer_text::NUMERIC IS DISTINCT FROM expected_pointer THEN RAISE EXCEPTION 'Committed Game Session terminal proof does not name the exact next pointer' USING ERRCODE = '23514'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index a965d0d621..a7889e218a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -9,6 +9,7 @@ import java.security.MessageDigest; import java.sql.Connection; import java.sql.SQLException; +import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; @@ -27,6 +28,8 @@ import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -507,6 +510,17 @@ void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { "account_selected_publication_sources", "account_game_logic_intake_sources", "account_game_logic_intake_source_read_sources"); + for (String guard : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_admission_settlement_insert_guard()")) { + assertThat( + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", guard) + .get(0, String.class)) + .contains("account_ss_admission_canonical_hold_next_pointer(original)"); + } } @Test @@ -633,7 +647,8 @@ void forgedWorldHoldDigestWithoutCanonicalPrefixCannotBecomeProtection() { .transaction() .executeWithoutResult( status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) - .hasMessageContaining("Admission hold identity differs from original instance and request"); + .hasMessageContaining( + "Original StartSession admission hold request differs from retained protection"); assertThat( fixture .dsl() @@ -790,6 +805,84 @@ void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { .isFalse(); } + @Test + void genuineFramedTerminalReceiptsReleaseRequiredSource() { + for (GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome : + List.of( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) { + Fixture fixture = fixture(); + acquire(fixture); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key())) + .hasMessageContaining("Original StartSession admission protection remains pending"); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(fixture.hold()), + outcome, + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + ? 1L + : null, + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + ? 1L + : null, + "sha256:" + "a".repeat(64), + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + Instant.now()); + byte[] ownerProof = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof); + long fence = + fixture + .dsl() + .fetchSingle( + "SELECT protection_fence FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()) + .get(0, Long.class); + byte[] evidence = + json( + Map.of( + "schema", "account-start-session-admission-protection-evidence/v1", + "accountProtectionId", fixture.protectionId().toString(), + "accountProtectionFence", Long.toString(fence), + "originalSourceCaptureReferenceBytesBase64", base64(bytes("{}")), + "originalSourceCaptureReferenceSha256", hash(bytes("{}")), + "requestBytesBase64", base64(fixture.request()), + "sourceEvidenceVector", List.of(base64(fixture.source().canonicalBytes())))); + byte[] terminal = + json( + Map.of( + "schema", "account-start-session-admission-protection-settlement/v1", + "canonicalAccountProtectionEvidenceBytesBase64", base64(evidence), + "canonicalGameSessionOwnerProofBytesBase64", base64(ownerProof))); + insert( + fixture.dsl(), + "account_start_session_admission_protection_settlements", + "protection_id", + fixture.protectionId(), + "outcome", + outcome.name(), + "terminal_bytes", + terminal, + "terminal_digest", + "sha256:" + hash(terminal)); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isTrue(); + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()); + } + } + @Test void expiredOriginalCannotRecoverEvenWhenRetainedIdentityAndSourcesRemain() { Fixture fixture = fixture(); @@ -971,6 +1064,86 @@ void acquisitionRejectsUnsettleableHoldRequestAndSourceSnapshotBounds() throws E "23514"); } + @Test + void acquisitionRejectsEveryHoldShapeThatSettlementCannotAccept() throws Exception { + Fixture fixture = fixture(); + var mapper = tools.jackson.databind.json.JsonMapper.builder().build(); + Map originalHold = + mapper.readValue(fixture.hold(), new tools.jackson.core.type.TypeReference<>() {}); + byte[] originalHoldRequest = + Base64.getDecoder().decode((String) originalHold.get("requestBytesBase64")); + Map requestEnvelope = + mapper.readValue(originalHoldRequest, new tools.jackson.core.type.TypeReference<>() {}); + @SuppressWarnings("unchecked") + Map requestFields = (Map) requestEnvelope.get("request"); + + Map uppercaseId = new LinkedHashMap<>(originalHold); + uppercaseId.put( + "holdId", ((String) uppercaseId.get("holdId")).toUpperCase(java.util.Locale.ROOT)); + assertMalformedHoldRejected(fixture, json(uppercaseId)); + + Map extraEnvelope = new LinkedHashMap<>(requestEnvelope); + extraEnvelope.put("extra", "unsettleable"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, json(extraEnvelope))); + + Map extraFields = new LinkedHashMap<>(requestFields); + extraFields.put("extra", "unsettleable"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(extraFields))); + + Map wrongType = new LinkedHashMap<>(requestFields); + wrongType.put("activeLifecycleEpoch", 1); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(wrongType))); + + assertMalformedHoldRejected( + fixture, + holdWithRequest( + originalHold, bytes(new String(originalHoldRequest, StandardCharsets.UTF_8) + " "))); + assertMalformedHoldRejected( + fixture, bytes(new String(fixture.hold(), StandardCharsets.UTF_8) + " ")); + + Map wrongOrigin = new LinkedHashMap<>(requestFields); + wrongOrigin.put("initialAdmissionOrigin", "EXPECT_CLOSED"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(wrongOrigin))); + + Map wrongPointer = new LinkedHashMap<>(requestFields); + wrongPointer.put("expectedPriorPointerVersion", "1"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(wrongPointer))); + + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + private static byte[] holdRequest(Map fields) { + return json( + Map.of("schema", "world-canonical-initial-admission-hold-request/v1", "request", fields)); + } + + private static byte[] holdWithRequest(Map originalHold, byte[] requestBytes) { + Map hold = new LinkedHashMap<>(originalHold); + hold.put("requestBytesBase64", base64(requestBytes)); + hold.put("holdBindingDigest", "sha256:" + hash(requestBytes)); + return json(hold); + } + + private static void assertMalformedHoldRejected(Fixture fixture, byte[] hold) throws Exception { + Map request = + tools.jackson.databind.json.JsonMapper.builder() + .build() + .readValue(fixture.request(), new tools.jackson.core.type.TypeReference<>() {}); + request.put("worldAdmissionHoldIdentityBytesBase64", base64(hold)); + assertDatabaseGuardFailure( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, hold, json(request))), + "23514"); + } + @Test void acquisitionAccepts256CompleteSourcesAndRejects257CompleteSources() { for (int sourceCount : List.of(256, 257)) { From 0c05e4f87a9e86ada789a55f9b48eb0bd18e8ded Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:08:59 +1300 Subject: [PATCH 15/28] Keep quarantined canonical actors isolated and require manual CI parent proof --- .github/workflows/ci.yml | 25 +++++++- .../runtime-and-data.md | 2 +- ...system-architecture-database-migrations.md | 2 +- .../gameplay-rules-entities-and-effects.md | 4 +- dev-tools/validation/check-flyway-versions.py | 49 +++++++++++++++- .../repository/CharacterRepository.java | 5 +- ...eseededActorAssignmentIntegrationTest.java | 58 +++++++++++++++---- 7 files changed, 128 insertions(+), 17 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c03ea3113e..2e9a5f8d41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,11 @@ on: pull_request: types: [opened, synchronize, reopened, edited] workflow_dispatch: + inputs: + flyway_base_sha: + description: Full immutable commit SHA of the receiving parent to compare Flyway history against + required: true + type: string run-name: CI — Validation ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }} @@ -555,6 +560,24 @@ jobs: with: fetch-depth: 0 + - name: Fetch manual Flyway parent when needed + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + FLYWAY_BASE_SHA: ${{ inputs.flyway_base_sha }} + run: | + if [[ ! "$FLYWAY_BASE_SHA" =~ ^[[:xdigit:]]{40}$ ]]; then + echo "workflow_dispatch requires a full immutable 40-character Flyway base SHA" >&2 + exit 1 + fi + if ! git cat-file -e "${FLYWAY_BASE_SHA}^{commit}" 2>/dev/null; then + git fetch --no-tags origin "$FLYWAY_BASE_SHA" + fi + resolved_sha="$(git rev-parse --verify "${FLYWAY_BASE_SHA}^{commit}")" + if [[ "${resolved_sha,,}" != "${FLYWAY_BASE_SHA,,}" ]]; then + echo "Flyway base SHA did not resolve to the requested commit" >&2 + exit 1 + fi + - name: ⚙️ Set Up Java uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6 with: @@ -576,7 +599,7 @@ jobs: - name: 🧪 Check Flyway Migration Versions env: - FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} run: ./gradlew checkFlywayVersions grpc-transport-config-sanity-checks: 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 d4105eb90e..a8c377679e 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -21,7 +21,7 @@ This document defines Entity Management’s runtime model, persistence ownership - 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. -- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude new `OWNER_RESOLVED` actors, including updates and condition expiry. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. +- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain legacy behavior. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The source services are manually composed and unregistered; no authenticated transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). - Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. Before any handler, service, or alternative snapshot writer is registered, this family must have an ADR 0163 retention declaration covering its class, terminal and reference blockers, compatible horizon, holds, metrics, cleanup cadence, and proved owner-local disposal. This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 3267c7c701..a2b9cbcbb0 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -47,7 +47,7 @@ This document is the current target authority for SQL persistence, schema owners - Saga tables are created inside the owning service schema via the shared `${serviceSchema}.saga_*` migrations rather than a separate dedicated `saga` schema. - New migrations are committed alongside service code so history stays with the owning service. -Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. Default Flyway ordering and validation remain enabled. Before allocating a new service-local version, inspect the immutable receiving parent’s complete effective migration set, including every shared location loaded by that service; the new version must be strictly greater than that combined local/shared frontier. A new shared migration must be strictly greater than every adopting service’s effective frontier, so a service-local extension cannot make the next shared migration an ignored lower version. Compare added artifacts against the receiving parent with the existing Flyway version checker, and prove fresh bootstrap and upgrade from the actual installed combined history. Re-version only never-applied candidate artifacts when correcting allocation; preserve their SQL bytes and every applied artifact’s filename and checksum. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. +Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. Default Flyway ordering and validation remain enabled. Before allocating a new service-local version, inspect the immutable receiving parent’s complete effective migration set, including every shared location loaded by that service; the new version must be strictly greater than that combined local/shared frontier. A new shared migration must be strictly greater than every adopting service’s effective frontier, so a service-local extension cannot make the next shared migration an ignored lower version. Compare added artifacts against the receiving parent with the existing Flyway version checker, and prove fresh bootstrap and upgrade from the actual installed combined history. A manually dispatched CI run must supply the receiving parent’s full immutable commit SHA; CI fetches that exact commit when needed and fails if it is unavailable so the same parent comparison remains in force. Re-version only never-applied candidate artifacts when correcting allocation; preserve their SQL bytes and every applied artifact’s filename and checksum. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. ### Objective Compatibility Gates 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 b00ea9eb2e..7a8b72e22c 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 @@ -117,7 +117,9 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Subsequent review corrections on develop `18f8063306c2ddb4337646de50b73619915a0e25` pass the full Entity gate: 236 unit cases executed in the first correction run and 26 physical PostgreSQL cases executed in the final gate, with zero failures, errors or skips. The new PostgreSQL proof checks Spring-proxy rejection without a caller-owned writable transaction and overlapping roster reads while preserving assignment writer exclusion. Both assignment digest paths use the same ordered encoder with literal `SHARED`/`ISOLATED` digest vectors, and run-owned capabilities admit release references through the documented 1,024-character bound. The canonical 79-leaf implementation-tracker check passes with actual migration file anchors. Account correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). These are bounded passive storage/source corrections; canonical runtime consumers and genuine owner admission remain open. -- Current passive-preparation proof is the final legacy-bridge isolation correction: the full Entity gate passed with 237 unit and 27 physical PostgreSQL integration cases, zero failures, errors or skips. Account's latest 20-case correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). The colliding numeric-tenant fixture proves that canonical actors and their inventory, equipment, friend, resource and condition rows are hidden from legacy readers, guarded writes reject canonical stored parents even when a legacy parent is supplied, and expiry preserves canonical conditions. Ordinary legacy reads, inserts, updates, deletes and expiry remain usable; exact canonical UUID, receipt and roster reads remain usable. The inventory-bearing positive case also exposed and corrected a missing inventory-version projection. A fresh, uncached TCP proto-generation and Java-compilation proof passes; the earlier source Runtime compiler failure remains unreproduced and does not supply current packaged runtime proof. The final allocated Hosted review is complete; its corrections require qualification and new published-head CI. +- Latest additional-review correction on `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` source inputs: the locked Entity gate passed in 1m30s, freshly executing 237 unit and 28 physical PostgreSQL cases with zero failures, errors or skips; jOOQ was up-to-date. The new collision variant quarantines an assigned canonical actor while retaining its canonical tenant provenance, then proves that legacy character, inventory, equipment, friend, resource, condition and expiry paths still exclude it. Legitimate quarantined legacy rows with null canonical tenant provenance remain usable; canonical receipt and roster readers exclude the quarantined actor. Formatting, compilation, static and documentation checks passed. The manual-CI parent selector, missing-parent failure and event cases pass the checker self-test, Ruff, workflow lint and YAML lint. Current published-head CI, additional Hosted/CLI reviews and fresh packaged runtime remain separate; full local Compose is paused for resource lifecycle tooling. + +- Prior passive-preparation proof is the original legacy-bridge isolation correction: the full Entity gate passed with 237 unit and 27 physical PostgreSQL integration cases, zero failures, errors or skips. Account's latest 20-case correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). The colliding numeric-tenant fixture proves that canonical actors and their inventory, equipment, friend, resource and condition rows are hidden from legacy readers, guarded writes reject canonical stored parents even when a legacy parent is supplied, and expiry preserves canonical conditions. Ordinary legacy reads, inserts, updates, deletes and expiry remain usable; exact canonical UUID, receipt and roster reads remain usable. The inventory-bearing positive case also exposed and corrected a missing inventory-version projection. A fresh, uncached TCP proto-generation and Java-compilation proof passes; the earlier source Runtime compiler failure remains unreproduced and does not supply current packaged runtime proof. The earlier Hosted allocation completed; later User-requested rounds and new published-head CI remain separate. - Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is 1005 with no out-of-order migrations. The 211 unit cases retain the preceding executed-run attribution and were up-to-date in the final 50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 0b0f2629f9..7fa5157bcd 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -67,7 +67,10 @@ def parent_snapshot(repo_root: Path, base_ref: str) -> Snapshot: # A branch name can move while validation runs. Require the caller's pinned commit. if not re.fullmatch(r"[0-9a-fA-F]{40}", base_ref): raise ValueError("--base-ref must be a full immutable 40-character commit SHA") - commit = git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}").decode().strip() + try: + commit = git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}").decode().strip() + except ValueError as error: + raise ValueError(f"immutable receiving parent commit is unavailable: {base_ref}; fetch that exact SHA") from error if commit.lower() != base_ref.lower(): raise ValueError("--base-ref must identify a commit directly") paths = git(repo_root, "ls-tree", "-r", "--name-only", commit, "services", "buildSrc").decode().splitlines() @@ -266,6 +269,7 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str raise AssertionError("mutable base ref was accepted") with tempfile.TemporaryDirectory() as tmp: + git(Path(tmp), "init", "-q") event_path = Path(tmp) / "event.json" sha = "1" * 40 for event, expected in [({"pull_request": {"base": {"sha": sha}}}, sha), @@ -273,6 +277,10 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str event_path.write_text(json.dumps(event), encoding="utf-8") if event_base_ref(str(event_path)) != expected: raise AssertionError(f"unexpected event base for {event}") + manual_event = {"inputs": {"flyway_base_sha": sha}} + event_path.write_text(json.dumps(manual_event), encoding="utf-8") + if event_base_ref(str(event_path)) != sha: + raise AssertionError("manual dispatch base SHA was not selected") # CI passes push metadata through the environment; the explicit option # must handle the same unborn-branch sentinel without reading Git history. @@ -287,6 +295,34 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str if result.returncode or "Parent frontier comparison" not in result.stdout: raise AssertionError(f"unborn explicit={explicit}: {result.stdout} {result.stderr}") + manual_environment = dict(os.environ) + manual_environment["FIREMUD_FLYWAY_BASE_REF"] = "1" * 40 + manual_environment["GITHUB_EVENT_NAME"] = "workflow_dispatch" + manual_environment["GITHUB_EVENT_PATH"] = str(event_path) + event_path.write_text(json.dumps({"inputs": {}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "requires a full immutable" not in result.stderr: + raise AssertionError(f"manual dispatch without a base was accepted: {result.stdout} {result.stderr}") + + event_path.write_text(json.dumps({"inputs": {"flyway_base_sha": "not-a-sha"}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "full immutable 40-character" not in result.stderr: + raise AssertionError(f"malformed manual dispatch base was accepted: {result.stdout} {result.stderr}") + + event_path.write_text(json.dumps({"inputs": {"flyway_base_sha": "0" * 40}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "requires a full immutable" not in result.stderr: + raise AssertionError(f"zero-sentinel manual dispatch base was accepted: {result.stdout} {result.stderr}") + + event_path.write_text(json.dumps({"inputs": {"flyway_base_sha": "2" * 40}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "immutable receiving parent commit is unavailable" not in result.stderr: + raise AssertionError(f"unavailable manual dispatch parent was accepted: {result.stdout} {result.stderr}") + print("Flyway migration sanity checker self-test passed.") @@ -297,6 +333,9 @@ def event_base_ref(event_path: str | None) -> str | None: pull_request = event.get("pull_request") if isinstance(pull_request, dict): return pull_request.get("base", {}).get("sha") + inputs = event.get("inputs") + if isinstance(inputs, dict): + return inputs.get("flyway_base_sha") before = event.get("before") # A newly created branch has no parent history in the push event. return before if before and before != "0" * 40 else None @@ -320,7 +359,13 @@ def main() -> int: return 0 root = args.root.resolve() try: - base_ref = args.base_ref or event_base_ref(os.environ.get("GITHUB_EVENT_PATH")) + event_path = os.environ.get("GITHUB_EVENT_PATH") + if os.environ.get("GITHUB_EVENT_NAME") == "workflow_dispatch": + base_ref = event_base_ref(event_path) + if not base_ref or base_ref == "0" * 40: + raise ValueError("workflow_dispatch requires a full immutable Flyway base SHA input") + else: + base_ref = args.base_ref or event_base_ref(event_path) # All input paths use GitHub's all-zero sentinel for a new branch. if base_ref == "0" * 40: base_ref = None 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 c94f061dc7..bcfe93da5d 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 @@ -150,7 +150,10 @@ public CharacterRepository(DSLContext dsl) { } static Condition legacyCharacterRow() { - return CHARACTERS.ACTOR_IDENTITY_STATUS.ne(ActorIdentityStatus.OWNER_RESOLVED.name()); + return CHARACTERS + .ACTOR_IDENTITY_STATUS + .ne(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.isNull()); } public Optional findWithInventoryById(Long id) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 7c8e6a633f..a24109b6a2 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -678,6 +678,16 @@ void committedReceiptIsExactReplayStableAndDeniedForChangedOrQuarantinedActor() @Test void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { + assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters(false); + } + + @Test + void numericTenantCollisionKeepsQuarantinedCanonicalActorOutOfLegacyReadersAndWriters() { + assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters(true); + } + + private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters( + boolean quarantined) { PreseededActorAssignmentResult assigned = assign( assignmentUuid, @@ -697,12 +707,37 @@ void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { "SELECT id FROM characters WHERE character_uuid = ?", Long.class, assigned.characterUuid()); + if (quarantined) { + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'AMBIGUOUS_ACCOUNT_NAMESPACE' WHERE id = ?", + canonicalCharacterId); + } + assertThat( + jdbcTemplate.queryForObject( + "SELECT tenant_uuid FROM characters WHERE id = ?", + UUID.class, + canonicalCharacterId)) + .isEqualTo(tenantUuid); + assertThat( + jdbcTemplate.queryForObject( + "SELECT actor_identity_status FROM characters WHERE id = ?", + String.class, + canonicalCharacterId)) + .isEqualTo(quarantined ? "QUARANTINED" : "OWNER_RESOLVED"); Long legacyCharacterId = jdbcTemplate.queryForObject( "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + "VALUES (23, 'Legacy Actor', ?, 'shared-live') RETURNING id", Long.class, entityTenantRowId); + assertThat( + jdbcTemplate.queryForObject( + "SELECT tenant_uuid IS NULL AND actor_identity_status = 'QUARANTINED' " + + "FROM characters WHERE id = ?", + Boolean.class, + legacyCharacterId)) + .isTrue(); Long itemId = jdbcTemplate.queryForObject( "INSERT INTO items (name, tenant_id) VALUES ('Legacy Item', ?) RETURNING id", @@ -797,7 +832,8 @@ void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { entityTenantRowId, namespaceUuid.toString(), "Canonical Actor")) .isEmpty(); assertThat(characterRepository.countByTenantId(entityTenantRowId)).isEqualTo(2); - assertThat(characterRepository.countQuarantinedByTenantId(entityTenantRowId)).isEqualTo(2); + assertThat(characterRepository.countQuarantinedByTenantId(entityTenantRowId)) + .isEqualTo(quarantined ? 3 : 2); assertThat(inventoryEntryRepository.countByCharacterTenantId(entityTenantRowId)).isEqualTo(1); assertThat(characterEquipmentRepository.countByCharacterTenantId(entityTenantRowId)) .isEqualTo(1); @@ -1018,14 +1054,16 @@ void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { PreseededActorAssignmentOwnerEvidence owner = evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); assertThat( - characterRepository.readPreseededActorAssignmentReceipt( - new PreseededActorAssignmentReceiptRequest( - assignmentUuid, - accountUuid, - assigned.characterUuid(), - assigned.intentDigest(), - assignmentRequest(owner).expectedTarget()))) - .isPresent(); + characterRepository + .readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + assignmentRequest(owner).expectedTarget())) + .isPresent()) + .isEqualTo(!quarantined); CanonicalGameplayRosterTarget rosterTarget = new CanonicalGameplayRosterTarget( tenantUuid, @@ -1068,7 +1106,7 @@ void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { rosterRequestUuid, accountUuid, rosterTarget, Instant.now())) .actors()) .extracting(actor -> actor.characterUuid()) - .containsExactly(assigned.characterUuid()); + .containsExactly(quarantined ? new UUID[0] : new UUID[] {assigned.characterUuid()}); } @Test From 9a3edf341bdced73c67e9b42d680222c75ac6c8e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:30:08 +1300 Subject: [PATCH 16/28] Align CI dispatch contract with immutable Flyway parent input --- .../tests/pr-retarget-workflow-contract.sh | 62 ++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 96af956069..97d69032a0 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -364,8 +364,66 @@ for filename in ("ci.yml", "security.yml", "license-scan.yml", "codeql.yml"): raise SystemExit("CodeQL must retain its weekly full-analysis schedule") if workflow["jobs"]["codeql-gate"]["if"] != "${{ always() && github.event_name == 'pull_request' }}": raise SystemExit("CodeQL Gate must cover every PR base and remain PR-only") - if set(events) != expected_events or events["workflow_dispatch"] not in ("", {}): - raise SystemExit(f"{filename} must retain exactly its supported events and manual dispatch") + if set(events) != expected_events: + raise SystemExit(f"{filename} must retain exactly its supported events") + if filename == "ci.yml": + dispatch = events["workflow_dispatch"] + if not isinstance(dispatch, dict) or set(dispatch) != {"inputs"}: + raise SystemExit("ci.yml manual dispatch must define only its Flyway parent input") + inputs = dispatch["inputs"] + if not isinstance(inputs, dict) or set(inputs) != {"flyway_base_sha"}: + raise SystemExit("ci.yml manual dispatch must require exactly flyway_base_sha") + base_input = inputs["flyway_base_sha"] + if ( + not isinstance(base_input, dict) + or set(base_input) != {"description", "required", "type"} + or base_input["required"] != "true" + or base_input["type"] != "string" + or "full immutable commit sha" not in base_input["description"].lower() + ): + raise SystemExit("ci.yml flyway_base_sha must be a required string describing the immutable parent SHA") + elif events["workflow_dispatch"] not in ("", {}): + raise SystemExit(f"{filename} must retain an empty manual dispatch") +PYTHON + +# Manual CI dispatch must pass and fetch its exact immutable Flyway parent. +python3 - "$ci_path" <<'PYTHON' +import sys +from pathlib import Path + +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) +job = workflow["jobs"]["flyway-migration-sanity-checks"] +steps = job["steps"] +fetch_steps = [step for step in steps if step.get("name") == "Fetch manual Flyway parent when needed"] +if len(fetch_steps) != 1: + raise SystemExit("CI must have exactly one manual Flyway parent fetch step") +fetch = fetch_steps[0] +if fetch.get("if") != "${{ github.event_name == 'workflow_dispatch' }}": + raise SystemExit("Flyway parent fetching must run only for manual dispatch") +if fetch.get("env") != {"FLYWAY_BASE_SHA": "${{ inputs.flyway_base_sha }}"}: + raise SystemExit("Flyway parent fetch must use the configured manual input") +fetch_script = fetch.get("run", "") +for required in ( + "^[[:xdigit:]]{40}$", + 'git cat-file -e "${FLYWAY_BASE_SHA}^{commit}"', + 'git fetch --no-tags origin "$FLYWAY_BASE_SHA"', + 'git rev-parse --verify "${FLYWAY_BASE_SHA}^{commit}"', +): + if required not in fetch_script: + raise SystemExit(f"Flyway parent fetch must validate and resolve the exact SHA: missing {required}") + +check_steps = [step for step in steps if step.get("name") == "🧪 Check Flyway Migration Versions"] +if len(check_steps) != 1: + raise SystemExit("CI must have exactly one Flyway version check step") +expected_base = ( + "${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha " + "|| github.event_name == 'pull_request' && github.event.pull_request.base.sha " + "|| github.event.before }}" +) +if check_steps[0].get("env", {}).get("FIREMUD_FLYWAY_BASE_REF") != expected_base: + raise SystemExit("Flyway version check must preserve dispatch, PR-base, and push-before parent selection") PYTHON # Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. From e872ab886eeb6842449a44f164ec9856ecf71b3f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:50:20 +1300 Subject: [PATCH 17/28] Validate committed lifecycle evidence before releasing Account source writers --- ...ivation_settlement_lifecycle_integrity.sql | 188 ++++++++ ...tionProtectionPostgresIntegrationTest.java | 401 ++++++++++++++++-- ...sionProtectionPostgresIntegrationTest.java | 13 +- 3 files changed, 557 insertions(+), 45 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql diff --git a/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql new file mode 100644 index 0000000000..a6555630e5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql @@ -0,0 +1,188 @@ +-- COMMITTED settlement must carry closed ACTIVE lifecycle evidence for the retained +-- PREPARING observation. Keep V1003's terminal, outcome, source and request guards installed. +-- This integrity guard does not authenticate World or duplicate its nested launch-binding codec: +-- launch binding and all immutable lifecycle values must remain exactly the retained owner values. +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; + request_value JSONB; + field_name TEXT; + region RECORD; + uuid_pattern CONSTANT TEXT := '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; + nil_uuid CONSTANT TEXT := '00000000-0000-0000-0000-000000000000'; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + -- Check before JSONB normalizes duplicate keys, including duplicates in nested objects. + IF NOT (convert_from(lifecycle_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Committed activation lifecycle requires unique closed JSON object keys' + USING ERRCODE = '23514'; + END IF; + lifecycle := convert_from(lifecycle_bytes, 'UTF8')::JSONB; + preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; + IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Committed activation lifecycle must be a closed object' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 12 + OR NOT (lifecycle ?& ARRAY[ + 'schema', 'request', 'launchBindingBytesBase64', 'startLocation', + 'runtimeRoomInstanceId', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion', + 'captureId', 'graphSha256', 'preparationInputDigest', 'operationalRegionAssignments']) + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR jsonb_typeof(lifecycle->'request') IS DISTINCT FROM 'object' + OR jsonb_typeof(lifecycle->'startLocation') IS DISTINCT FROM 'object' + OR jsonb_typeof(lifecycle->'operationalRegionAssignments') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Committed activation lifecycle must be closed ACTIVE owner evidence' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; + FOREACH field_name IN ARRAY ARRAY[ + 'schema', 'launchBindingBytesBase64', 'runtimeRoomInstanceId', 'lifecycleStatus', + 'lifecycleEpoch', 'rowVersion', 'captureId', 'graphSha256', 'preparationInputDigest'] LOOP + IF jsonb_typeof(lifecycle->field_name) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation lifecycle scalar must be a string: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOREACH field_name IN ARRAY ARRAY['runtimeRoomInstanceId', 'lifecycleEpoch', 'rowVersion'] LOOP + IF lifecycle->>field_name !~ '^(0|[1-9][0-9]*)$' + OR (lifecycle->>field_name)::NUMERIC > 9223372036854775807 + OR (field_name <> 'rowVersion' AND (lifecycle->>field_name)::NUMERIC = 0) THEN + RAISE EXCEPTION 'Committed activation lifecycle counter is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF lifecycle->>'captureId' !~ uuid_pattern OR lifecycle->>'captureId' = nil_uuid + OR lifecycle->>'graphSha256' !~ '^[0-9a-f]{64}$' + OR lifecycle->>'preparationInputDigest' !~ '^sha256:[0-9a-f]{64}$' + OR length(lifecycle->>'launchBindingBytesBase64') = 0 + OR regexp_replace(encode(decode(lifecycle->>'launchBindingBytesBase64', 'base64'), + 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle->>'launchBindingBytesBase64' THEN + RAISE EXCEPTION 'Committed activation lifecycle identities or retained launch bytes are invalid' + USING ERRCODE = '23514'; + END IF; + request_value := lifecycle->'request'; + IF (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 14 + OR NOT (request_value ?& ARRAY[ + 'schemaVersion', 'readRequestId', 'targetNamespace', 'canonicalTenantId', 'worldSlug', + 'canonicalGameInstanceId', 'playableStateNamespaceId', 'playableStateScope', + 'publicProduction', 'controlPlaneRequestId', 'canonicalVersionId', + 'expectedDescriptorRequestDigest', 'expectedDescriptorResultDigest', + 'expectedReleaseAttestationDigest']) + OR jsonb_typeof(request_value->'schemaVersion') IS DISTINCT FROM 'number' + OR request_value->>'schemaVersion' IS DISTINCT FROM '1' + OR request_value->'publicProduction' IS DISTINCT FROM 'true'::JSONB + OR request_value->>'playableStateScope' IS DISTINCT FROM 'SHARED' THEN + RAISE EXCEPTION 'Committed activation lifecycle request must have the complete closed shape' + USING ERRCODE = '23514'; + END IF; + FOREACH field_name IN ARRAY ARRAY[ + 'readRequestId', 'targetNamespace', 'canonicalTenantId', 'worldSlug', + 'canonicalGameInstanceId', 'playableStateNamespaceId', 'playableStateScope', + 'controlPlaneRequestId', 'canonicalVersionId', 'expectedDescriptorRequestDigest', + 'expectedDescriptorResultDigest', 'expectedReleaseAttestationDigest'] LOOP + IF jsonb_typeof(request_value->field_name) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation lifecycle request scalar must be a string: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOREACH field_name IN ARRAY ARRAY[ + 'readRequestId', 'canonicalTenantId', 'canonicalGameInstanceId', + 'playableStateNamespaceId', 'canonicalVersionId'] LOOP + IF request_value->>field_name !~ uuid_pattern OR request_value->>field_name = nil_uuid THEN + RAISE EXCEPTION 'Committed activation lifecycle request UUID is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOREACH field_name IN ARRAY ARRAY[ + 'expectedDescriptorRequestDigest', 'expectedDescriptorResultDigest', + 'expectedReleaseAttestationDigest'] LOOP + IF request_value->>field_name !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Committed activation lifecycle request digest is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF length(request_value->>'targetNamespace') NOT BETWEEN 1 AND 63 + OR request_value->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + OR octet_length(request_value->>'worldSlug') NOT BETWEEN 1 AND 120 + OR request_value->>'worldSlug' !~ '^[a-z0-9]+(-[a-z0-9]+)*$' + OR length(request_value->>'controlPlaneRequestId') NOT BETWEEN 1 AND 128 + OR request_value->>'controlPlaneRequestId' ~ '^[[:space:]]*$' THEN + RAISE EXCEPTION 'Committed activation lifecycle request text is invalid' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(lifecycle->'startLocation')) <> 3 + OR NOT (lifecycle->'startLocation' ?& ARRAY['tenantId', 'versionId', 'roomTemplateId']) THEN + RAISE EXCEPTION 'Committed activation lifecycle start location must be closed' + USING ERRCODE = '23514'; + END IF; + FOREACH field_name IN ARRAY ARRAY['tenantId', 'versionId', 'roomTemplateId'] LOOP + IF jsonb_typeof(lifecycle->'startLocation'->field_name) IS DISTINCT FROM 'string' + OR lifecycle->'startLocation'->>field_name !~ uuid_pattern + OR lifecycle->'startLocation'->>field_name = nil_uuid THEN + RAISE EXCEPTION 'Committed activation lifecycle start location UUID is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF (SELECT count(*) FROM jsonb_object_keys(lifecycle->'operationalRegionAssignments')) = 0 + OR (SELECT count(*) FROM jsonb_each(lifecycle->'operationalRegionAssignments')) + <> (SELECT count(DISTINCT value) FROM jsonb_each(lifecycle->'operationalRegionAssignments')) THEN + RAISE EXCEPTION 'Committed activation lifecycle requires distinct operational region assignments' + USING ERRCODE = '23514'; + END IF; + FOR region IN SELECT key, value FROM jsonb_each(lifecycle->'operationalRegionAssignments') LOOP + IF region.key !~ uuid_pattern OR region.key = nil_uuid + OR jsonb_typeof(region.value) IS DISTINCT FROM 'string' + OR region.value #>> '{}' !~ uuid_pattern OR region.value #>> '{}' = nil_uuid + OR region.key = region.value #>> '{}' THEN + RAISE EXCEPTION 'Committed activation lifecycle region assignment is invalid' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN NEW; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Committed activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_settlement_validate_lifecycle + BEFORE INSERT ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_lifecycle_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 52131fd8be..935b801f37 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -18,6 +18,8 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -36,8 +38,8 @@ import tools.jackson.databind.json.JsonMapper; /** - * Runs V1003 against the actual Account PostgreSQL schema and assembled source-writer guard. The - * integrity and currentness fixtures seed related owner rows with upstream producer triggers + * Runs V1003/V1004 against the actual Account PostgreSQL schema and assembled source-writer guard. + * The integrity and currentness fixtures seed related owner rows with upstream producer triggers * disabled. Protection acquisition, child completeness, settlement and source-writer guards remain * enabled; they prove SQL currentness/exclusion/immutability only, not authenticated * activation-protection production. @@ -51,8 +53,8 @@ class AccountStartSessionActivationProtectionPostgresIntegrationTest { private static final JsonMapper JSON = JsonMapper.builder().build(); @Test - void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() throws Exception { - Fixture fixture = fixture(); + void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() throws Exception { + Fixture fixture = fixture("1003"); CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(10), 135500); byte[] requestBinding = current.requestBytes(); Map request = readJson(requestBinding); @@ -123,15 +125,62 @@ void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() thr sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNull(); + String retainedHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004' ORDER BY installed_rank"; + var installedHistory = fixture.dsl().fetch(retainedHistoryQuery).getValues(0, String.class); + String protectionRowsQuery = + "SELECT row_to_json(p)::TEXT FROM " + + "account_start_session_activation_protections p ORDER BY activation_protection_id"; + String sourceRowsQuery = + "SELECT row_to_json(s)::TEXT FROM " + + "account_start_session_activation_protection_sources s ORDER BY activation_protection_id, source_key"; + var pendingRows = fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class); + var retainedSources = fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class); + assertThat(pendingRows).hasSize(1); + assertThat(retainedSources).hasSize(2); + + Flyway upgrade = activationFlyway(fixture.dataSource(), "latest"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); + assertThat(fixture.dsl().fetch(retainedHistoryQuery).getValues(0, String.class)) + .isEqualTo(installedHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT max(version::int) FROM flyway_schema_history WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1004); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + fixture .dsl() .fetch( "SELECT pg_sleep(GREATEST(0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", current.expiryText()); - // This synthetic SQL receipt proves only that V1003 permits a source writer after an immutable - // terminal-shaped row is committed. It is not a typed receipt or authenticated World producer - // proof. The original lease has expired before settlement insertion. + // This SQL receipt retains a typed closed ACTIVE lifecycle fixture. Upstream owner rows remain + // stipulated; this is storage integrity proof, not authenticated World production. + // The original lease has expired before settlement insertion. OffsetDateTime retainedAcquiredAt = stored.get("acquired_at", OffsetDateTime.class); long protectionFence = stored.get("activation_protection_fence", Long.class); byte[] accountEvidenceBytes = @@ -145,6 +194,149 @@ void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() thr byte[] activationResultBytes = activationResult(activationRequestId, preparingEvidence, "COMMITTED"); + Map validResult = readJson(activationResultBytes); + byte[] activeBytes = + Base64.getDecoder().decode((String) validResult.get("lifecycleEvidenceBytesBase64")); + java.util.List invalidLifecycleCarriers = new java.util.ArrayList<>(); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("synthetic ACTIVE"))); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("{"))); + invalidLifecycleCarriers.add( + Base64.getEncoder().encodeToString(new byte[] {(byte) 0xc3, 0x28})); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("null"))); + invalidLifecycleCarriers.add( + Base64.getEncoder() + .encodeToString( + bytes( + new String(activeBytes, StandardCharsets.UTF_8) + .replace("\"schemaVersion\":1", "\"schemaVersion\":1.0")))); + String activeJson = new String(activeBytes, StandardCharsets.UTF_8); + for (String duplicate : + new String[] { + activeJson.replace("\"schema\":", "\"schema\":\"wrong/v1\",\"schema\":"), + activeJson.replace( + "\"lifecycleStatus\":", "\"lifecycleStatus\":\"PREPARING\",\"lifecycleStatus\":"), + activeJson.replace("\"schemaVersion\":1", "\"schemaVersion\":0,\"schemaVersion\":1") + }) { + byte[] duplicateBytes = bytes(duplicate); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(duplicateBytes)) + .isInstanceOf(IllegalArgumentException.class); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(duplicateBytes)); + } + invalidLifecycleCarriers.add("%%%"); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(activeBytes) + "\n"); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("[]"))); + for (String field : + new String[] { + "schema", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion", + "runtimeRoomInstanceId", + "captureId", + "graphSha256", + "preparationInputDigest", + "launchBindingBytesBase64", + "startLocation", + "operationalRegionAssignments", + "request" + }) { + Map missing = readJson(activeBytes); + missing.remove(field); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(missing))); + Map wrongType = readJson(activeBytes); + wrongType.put(field, 1); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(wrongType))); + } + for (Map.Entry change : + Map.ofEntries( + Map.entry("schema", "wrong/v1"), + Map.entry("lifecycleStatus", "PREPARING"), + Map.entry("lifecycleEpoch", "0"), + Map.entry("rowVersion", "01"), + Map.entry("runtimeRoomInstanceId", "9223372036854775808"), + Map.entry("captureId", UUID.randomUUID().toString()), + Map.entry("graphSha256", "a".repeat(64)), + Map.entry("preparationInputDigest", "sha256:" + "a".repeat(64)), + Map.entry("launchBindingBytesBase64", "e30="), + Map.entry("startLocation", Map.of()), + Map.entry("operationalRegionAssignments", Map.of()), + Map.entry("extra", true)) + .entrySet()) { + Map changed = readJson(activeBytes); + changed.put(change.getKey(), change.getValue()); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(changed))); + } + for (String field : + new String[] { + "canonicalGameInstanceId", + "controlPlaneRequestId", + "readRequestId", + "schemaVersion", + "publicProduction", + "extra" + }) { + Map changed = readJson(activeBytes); + @SuppressWarnings("unchecked") + Map changedLifecycleRequest = (Map) changed.get("request"); + changedLifecycleRequest.put( + field, + "canonicalGameInstanceId".equals(field) ? UUID.randomUUID().toString() : "changed"); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(changed))); + } + for (String status : new String[] {"FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"}) { + Map changed = readJson(activeBytes); + changed.put("lifecycleStatus", status); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(changed))); + } + for (String carrier : invalidLifecycleCarriers) { + Map invalidResult = readJson(activationResultBytes); + invalidResult.put("lifecycleEvidenceBytesBase64", carrier); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(invalidResult)); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + + Map invalidTerminalCode = readJson(activationResultBytes); + invalidTerminalCode.put("terminalCode", "FENCED_ABORT"); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(invalidTerminalCode)); + Map invalidOutcome = readJson(activationResultBytes); + invalidOutcome.put("outcome", "ABORTED"); + invalidOutcome.put("terminalCode", "FENCED_ABORT"); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(invalidOutcome)); + Map changedCapture = readJson(accountEvidenceBytes); byte[] wrongCapture = bytes("substituted capture reference"); changedCapture.put( @@ -342,6 +534,88 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); } + @Test + void abortedSettlementPreservesTerminalCodeFenceWithoutRequiringActiveLifecycle() + throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(60)); + acquireProtection(fixture, current); + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at " + + "FROM account_start_session_activation_protections"); + UUID id = stored.get("activation_protection_id", UUID.class); + long fence = stored.get("activation_protection_fence", Long.class); + Map request = readJson(current.requestBytes()); + UUID activationId = UUID.fromString((String) request.get("worldActivationRequestId")); + var sources = + fixture + .dsl() + .fetch( + "SELECT source_key, source_evidence FROM " + + "account_start_session_activation_protection_sources " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)"); + byte[] evidence = + accountEvidence( + id, + fence, + stored.get("acquired_at", OffsetDateTime.class), + current.requestBytes(), + bytes("{}"), + sources.stream() + .map(row -> row.get("source_evidence", byte[].class)) + .toArray(byte[][]::new)); + Map result = + readJson( + activationResult( + activationId, + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")), + "ABORTED")); + result.put("lifecycleEvidenceBytesBase64", null); + result.put("terminalCode", ""); + assertSettlementInsertRejected( + fixture, id, fence, activationId, evidence, jsonBytes(result), "ABORTED"); + result.put("terminalCode", null); + assertSettlementInsertRejected( + fixture, id, fence, activationId, evidence, jsonBytes(result), "ABORTED"); + result.put("terminalCode", "FENCED_ABORT"); + byte[] terminal = terminalBytes(id, fence, activationId, evidence, jsonBytes(result)); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + fence, + "world_activation_request_id", + activationId, + "world_activation_fence", + 29L, + "outcome", + "ABORTED", + "account_protection_evidence_bytes", + evidence, + "terminal_bytes", + terminal, + "terminal_digest", + "sha256:" + hash(terminal))); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sources.get(0).get("source_key", String.class))); + } + private static void assertSettlementInsertRejected( Fixture fixture, UUID protectionId, @@ -349,6 +623,24 @@ private static void assertSettlementInsertRejected( UUID activationRequestId, byte[] protectionEvidenceBytes, byte[] activationResultBytes) { + assertSettlementInsertRejected( + fixture, + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes, + "COMMITTED"); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes, + String outcome) { byte[] terminalBytes = terminalBytes( protectionId, @@ -374,7 +666,7 @@ private static void assertSettlementInsertRejected( "world_activation_fence", 29L, "outcome", - "COMMITTED", + outcome, "account_protection_evidence_bytes", protectionEvidenceBytes, "terminal_bytes", @@ -391,7 +683,10 @@ private static void assertSettlementInsertRejected( assertThat(postgresFailure) .isInstanceOfSatisfying( org.postgresql.util.PSQLException.class, - sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); }); } @@ -425,6 +720,16 @@ private static byte[] accountEvidenceBytes(Map value) throws Exc private static byte[] activationResult( UUID activationRequestId, byte[] preparingEvidence, String outcome) throws Exception { + Map active = readJson(preparingEvidence); + active.put("lifecycleStatus", "ACTIVE"); + active.put("lifecycleEpoch", "4"); + active.put("rowVersion", "1"); + @SuppressWarnings("unchecked") + Map activeRequest = (Map) active.get("request"); + activeRequest.put("readRequestId", UUID.randomUUID().toString()); + byte[] activeBytes = jsonBytes(active); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(activeBytes).lifecycleStatus()) + .isEqualTo("ACTIVE"); Map preparing = readJson(preparingEvidence); @SuppressWarnings("unchecked") Map lifecycleRequest = (Map) preparing.get("request"); @@ -444,9 +749,7 @@ private static byte[] activationResult( "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); result.put("outcome", outcome); result.put("terminalCode", "COMMITTED".equals(outcome) ? null : "FENCED_ABORT"); - result.put( - "lifecycleEvidenceBytesBase64", - Base64.getEncoder().encodeToString(bytes("synthetic ACTIVE"))); + result.put("lifecycleEvidenceBytesBase64", Base64.getEncoder().encodeToString(activeBytes)); return jsonBytes(result); } @@ -511,7 +814,10 @@ private static void assertCurrentnessRejected( assertThat(postgresFailure) .isInstanceOfSatisfying( org.postgresql.util.PSQLException.class, - sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); }); } @@ -522,8 +828,10 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original private static CurrentnessCase currentnessCase( Fixture fixture, Instant originalLease, int padding) throws Exception { - UUID tenantId = UUID.randomUUID(); - UUID gameInstanceId = UUID.randomUUID(); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("PREPARING", 3L); + UUID tenantId = lifecycle.request().canonicalTenantId(); + UUID gameInstanceId = lifecycle.request().canonicalGameInstanceId(); UUID participationId = UUID.randomUUID(); UUID ownerMutationId = UUID.randomUUID(); UUID ownerAttemptId = UUID.randomUUID(); @@ -534,7 +842,7 @@ private static CurrentnessCase currentnessCase( long issuanceFence = 9L; long sourceVersion = 13L; long sourceFence = 17L; - String requestId = "original-activation/" + UUID.randomUUID(); + String requestId = lifecycle.request().controlPlaneRequestId(); String fingerprint = "arfp/v1/activation-test/" + "a".repeat(64); OffsetDateTime dbNow = fixture.dsl().fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); @@ -617,22 +925,19 @@ private static CurrentnessCase currentnessCase( String preparationDigest = "sha256:" + hash(bytes(preparationInput)); byte[] worldPreparing = - jsonBytes( - Map.of( - "schema", - "world-canonical-instance-lifecycle-evidence/v1", - "request", - Map.of( - "controlPlaneRequestId", - requestId, - "targetNamespace", - "test", - "canonicalTenantId", - tenantId.toString(), - "canonicalGameInstanceId", - gameInstanceId.toString()), - "lifecycleStatus", - "PREPARING")); + new WorldCanonicalInstanceLifecycleEvidence( + lifecycle.request(), + lifecycle.launchBinding(), + lifecycle.startLocation(), + lifecycle.runtimeRoomInstanceId(), + "PREPARING", + lifecycle.lifecycleEpoch(), + lifecycle.rowVersion(), + lifecycle.captureId(), + lifecycle.graphSha256(), + preparationDigest, + lifecycle.operationalRegionAssignments()) + .canonicalBytes(); byte[] launchRead = bytes("synthetic exact STARTING read"); byte[] operationIdentity = bytes("activation operation identity"); String operationDigest = "sha256:" + hash(operationIdentity); @@ -971,25 +1276,33 @@ private static byte[] jsonBytes(Object value) throws Exception { } private static Fixture fixture() { + return fixture("latest"); + } + + private static Fixture fixture(String target) { String schema = "ss_activation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource source = new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); source.setSchema(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + activationFlyway(source, target).migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); TransactionTemplate transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); String requestId = "activation-test/" + UUID.randomUUID(); - return new Fixture(dsl, transaction, requestId); + return new Fixture(dsl, transaction, requestId, source); + } + + private static Flyway activationFlyway(DriverManagerDataSource source, String target) { + return Flyway.configure() + .dataSource(source) + .schemas(source.getSchema()) + .defaultSchema(source.getSchema()) + .placeholders(Map.of("serviceSchema", source.getSchema())) + .locations("classpath:db/migration") + .target(target) + .load(); } private static void insert(DSLContext dsl, String table, Object... fields) { @@ -1012,7 +1325,11 @@ private static String hash(byte[] bytes) { } } - private record Fixture(DSLContext dsl, TransactionTemplate transaction, String requestId) {} + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + String requestId, + DriverManagerDataSource dataSource) {} private record CurrentnessCase( byte[] requestBytes, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index a7889e218a..75f4a17f86 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -193,12 +193,12 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua dsl.fetchSingle( "SELECT count(*) FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(113L); + .isEqualTo(114L); assertThat( dsl.fetchSingle( "SELECT max(version::int) FROM flyway_schema_history_account_service WHERE version ~ '^[0-9]+$'") .get(0, Integer.class)) - .isEqualTo(1003); + .isEqualTo(1004); assertThat( dsl.fetchSingle( "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", @@ -264,7 +264,14 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesSourcePr .fetchSingle( "SELECT count(*) FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND success") .get(0, Long.class)) - .isEqualTo(113L); + .isEqualTo(114L); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT max(version::int) FROM flyway_schema_history_account_service WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1004); assertThat( parent .dsl() From 02401d4df0276b04c7f0ff780441a050c4b72fc8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:04:12 +1300 Subject: [PATCH 18/28] Reject ambiguous lifecycle numbers and record final settlement proof --- .../account-service/runtime-and-data.md | 2 ++ .../player-access-and-session.md | 6 ++++-- ...4__activation_settlement_lifecycle_integrity.sql | 6 ++++++ ...ActivationProtectionPostgresIntegrationTest.java | 13 +++++++------ 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index a11206fa36..64b7f6837d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -338,4 +338,6 @@ Account retains admission and activation protection separately from the original The existing Account source-lock order remains canonical: source-key locks precede protection-row locks, and NOWAIT refuses a reversed or unavailable acquisition. Pending admission or activation blocks the existing source-hold, source-change and hosted-terms disclosure paths until the distinct protection has its exact immutable terminal settlement. Expiry, World receiving settlement, absence and an asserted outcome cannot release another protection. Settlement stores the complete original protection and exact terminal binding; these SQL checks validate integrity and do not authenticate the terminal producer. The owner obligations remain defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). +Forward [V1004 lifecycle integrity](../../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql) additionally requires a COMMITTED activation settlement to retain closed ACTIVE lifecycle evidence bound to the original PREPARING request and immutable owner values. Malformed or ambiguous lifecycle carriers retain the pending source-writer exclusion; exact ABORTED terminal handling remains separate. This storage validation does not authenticate World or activate the source path. Current proof and limits belong in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). + V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. 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 8d3647ff48..88683ad9f9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,13 +12,15 @@ The Account source-currentness/first-JOIN persistence stage builds on the tested ### Original StartSession source-protection storage -The bounded V1003 receiving cut adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. +The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). The subsequent Hosted/CLI correction on develop `18f8063306c2ddb4337646de50b73619915a0e25` executed 18 focused Account PostgreSQL cases with zero failures, errors or skips. Acquisition now rejects admission data that cannot satisfy immutable settlement bounds; committed activation fixtures run the acquisition, source-child and deferred-completeness guards. The proof includes the 256-source boundary, canonical Base64 and UTF-16 ordering, a complete activation tuple above 135,168 bytes, and settlement after lease expiry. Actual jOOQ generation, compilation, integration Checkstyle and SpotBugs, formatting and documentation checks passed. This corrects the bounded fixture proof; the older broad source-CI counts remain historical and do not qualify the changed SQL or establish genuine owner production. -The latest local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. +The additional review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. + +The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. ### Entity character-creation denial diff --git a/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql index a6555630e5..2c0e791916 100644 --- a/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql +++ b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql @@ -42,6 +42,12 @@ BEGIN RAISE EXCEPTION 'Committed activation lifecycle requires unique closed JSON object keys' USING ERRCODE = '23514'; END IF; + -- JSON preserves the number spelling that JSONB may normalize (for example 1e0). + IF (convert_from(lifecycle_bytes, 'UTF8')::JSON->'request'->'schemaVersion')::TEXT + IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Committed activation lifecycle schemaVersion must be the integral JSON number 1' + USING ERRCODE = '23514'; + END IF; lifecycle := convert_from(lifecycle_bytes, 'UTF8')::JSONB; preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' THEN diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 935b801f37..87e49c05f8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -203,13 +203,14 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro invalidLifecycleCarriers.add( Base64.getEncoder().encodeToString(new byte[] {(byte) 0xc3, 0x28})); invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("null"))); - invalidLifecycleCarriers.add( - Base64.getEncoder() - .encodeToString( - bytes( - new String(activeBytes, StandardCharsets.UTF_8) - .replace("\"schemaVersion\":1", "\"schemaVersion\":1.0")))); String activeJson = new String(activeBytes, StandardCharsets.UTF_8); + for (String schemaVersion : new String[] {"1.0", "1e0", "1e+0"}) { + byte[] invalidVersion = + bytes(activeJson.replace("\"schemaVersion\":1", "\"schemaVersion\":" + schemaVersion)); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(invalidVersion)) + .isInstanceOf(IllegalArgumentException.class); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(invalidVersion)); + } for (String duplicate : new String[] { activeJson.replace("\"schema\":", "\"schema\":\"wrong/v1\",\"schema\":"), From d2f3b7e2e3166939cfe1cbe2b33ea8d50d7ada90 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:22:49 +1300 Subject: [PATCH 19/28] Strengthen effective Flyway history and protection regression proof --- .../player-access-and-session.md | 2 +- dev-tools/validation/check-flyway-versions.py | 45 +++++++++++++++- ...tionProtectionPostgresIntegrationTest.java | 2 +- ...sionProtectionPostgresIntegrationTest.java | 54 +++++++++---------- ...reseededActorAssignmentCapabilityTest.java | 7 +-- 5 files changed, 76 insertions(+), 34 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 88683ad9f9..be78b8ed5a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -156,7 +156,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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. `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; genuine owner acquisition and authenticated terminal-settlement producers remain open. | +| `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; genuine owner acquisition and authenticated terminal-settlement producers remain open. | | `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`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 7fa5157bcd..ff1362473a 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -161,9 +161,10 @@ def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str seen[item.version_key] = item previous = parent_grouped.get(project, []) + previous_paths = {item.path for item in previous} frontier = max((item.version_key for item in previous), default=None) for item in items: - if parent is not None and item.path not in parent and frontier is not None and item.version_key <= frontier: + if parent is not None and item.path not in previous_paths and frontier is not None and item.version_key <= frontier: issues.append(f"services/{project}: new migration {item.path} (V{item.version_text}) " f"must exceed effective parent frontier V{version_label(frontier)}") @@ -210,6 +211,48 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str check("duplicate-only without a base", history, None, None) check("new low local", {**history, local + "V2__new.sql": b"-- new"}, history, "frontier V1002") check("forward local", {**history, local + "V1003__new.sql": b"-- new"}, history, None) + + unadopted_parent = { + "services/example-service/build.gradle.kts": b"dependencies {}", + "services/example-service/src/main/resources/application.yml": + b"spring:\n flyway:\n locations: classpath:db/migration\n", + local + "V2000__init.sql": b"-- local\n", + shared + "V1000__saga_a.sql": b"-- shared a\n", + shared + "V1001__saga_b.sql": b"-- shared b\n", + shared + "V1002__saga_c.sql": b"-- shared c\n", + } + newly_adopted = { + **unadopted_parent, + "services/example-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], + "services/example-service/src/main/resources/application.yml": + wiring["services/example-service/src/main/resources/application.yml"], + } + check("newly effective shared history below local frontier", newly_adopted, unadopted_parent, "frontier V2000") + check("unchanged non-adopter with raw shared history", unadopted_parent, unadopted_parent, None) + + forward_parent = {path: data for path, data in unadopted_parent.items() + if path != local + "V2000__init.sql"} + forward_parent[local + "V999__init.sql"] = b"-- local\n" + forward_adopted = { + **forward_parent, + "services/example-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], + "services/example-service/src/main/resources/application.yml": + wiring["services/example-service/src/main/resources/application.yml"], + shared + "V1003__saga_forward.sql": b"-- forward shared\n", + } + check("newly effective shared history above local frontier", forward_adopted, forward_parent, None) + + test_only_parent = { + **unadopted_parent, + "services/example-service/src/main/resources/application.yml": wiring["services/example-service/src/main/resources/application.yml"], + } + test_only_forward = { + **test_only_parent, + "services/example-service/build.gradle.kts": b'testImplementation(project(":common-saga"))', + local + "V2001__forward.sql": b"-- new local\n", + } + check("test-only saga dependency does not adopt shared migrations", test_only_forward, test_only_parent, None) + advanced = {**history, local + "V1005__later.sql": b"-- later"} check("shared below adopter frontier", {**advanced, shared + "V1004__new.sql": b"-- new"}, advanced, "frontier V1005") check("forward shared", {**advanced, shared + "V1006__new.sql": b"-- new"}, advanced, None) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 87e49c05f8..8fecbdebeb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -148,7 +148,7 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro assertThat(pendingRows).hasSize(1); assertThat(retainedSources).hasSize(2); - Flyway upgrade = activationFlyway(fixture.dataSource(), "latest"); + Flyway upgrade = activationFlyway(fixture.dataSource(), "1004"); assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); upgrade.validate(); assertThat(fixture.dsl().fetch(retainedHistoryQuery).getValues(0, String.class)) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 75f4a17f86..fbfedc3a4c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -33,6 +33,8 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationState; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Field; @@ -186,19 +188,12 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); source.setSchema(schema); - actualParentFlyway(source, "classpath:db/migration", "classpath:db/migration/saga").migrate(); - actualParentFlyway(source, "classpath:db/migration", "classpath:db/migration/saga").validate(); + Flyway current = + actualParentFlyway(source, "classpath:db/migration", "classpath:db/migration/saga"); + current.migrate(); + current.validate(); + assertCurrentMigrationsInstalled(current); var dsl = DSL.using(source, SQLDialect.POSTGRES); - assertThat( - dsl.fetchSingle( - "SELECT count(*) FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND success") - .get(0, Long.class)) - .isEqualTo(114L); - assertThat( - dsl.fetchSingle( - "SELECT max(version::int) FROM flyway_schema_history_account_service WHERE version ~ '^[0-9]+$'") - .get(0, Integer.class)) - .isEqualTo(1004); assertThat( dsl.fetchSingle( "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", @@ -246,8 +241,11 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesSourcePr assertThat(checksums).hasSize(112); var capture = retainedPhysicalRows(parent, "account_start_session_authority_captures"); - actualParentFlyway(parent, "classpath:db/migration", "classpath:db/migration/saga").migrate(); - actualParentFlyway(parent, "classpath:db/migration", "classpath:db/migration/saga").validate(); + Flyway current = + actualParentFlyway(parent, "classpath:db/migration", "classpath:db/migration/saga"); + current.migrate(); + current.validate(); + assertCurrentMigrationsInstalled(current); assertThat( parent @@ -258,20 +256,6 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesSourcePr .isEqualTo(checksums); assertThat(retainedPhysicalRows(parent, "account_start_session_authority_captures")) .isEqualTo(capture); - assertThat( - parent - .dsl() - .fetchSingle( - "SELECT count(*) FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND success") - .get(0, Long.class)) - .isEqualTo(114L); - assertThat( - parent - .dsl() - .fetchSingle( - "SELECT max(version::int) FROM flyway_schema_history_account_service WHERE version ~ '^[0-9]+$'") - .get(0, Integer.class)) - .isEqualTo(1004); assertThat( parent .dsl() @@ -281,6 +265,20 @@ void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesSourcePr .isNotNull(); } + private static void assertCurrentMigrationsInstalled(Flyway flyway) { + var migrations = flyway.info().all(); + assertThat(migrations) + .isNotEmpty() + .allSatisfy( + migration -> + assertThat(migration.getState()) + .as(migration.getScript()) + .isEqualTo(MigrationState.SUCCESS)); + assertThat(migrations) + .extracting(MigrationInfo::getVersion) + .contains(MigrationVersion.fromVersion("1003"), MigrationVersion.fromVersion("1004")); + } + private static Flyway actualParentFlyway(Fixture fixture, String... locations) { return actualParentFlyway(fixture.dataSource(), locations); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java index 88801be61c..77f822a23f 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java @@ -198,16 +198,17 @@ void trustRootPinRequiresOneValidCaAndUsesExactLoadedCertificateFingerprint() th new TrustManager[] {loadedTrustManager}, configuredFingerprint)) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); - doThrow(new CertificateExpiredException()).when(trustedRoot).checkValidity(); assertThatThrownBy( () -> RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( - List.of(trustedRoot))) + List.of(trustedRoot, trustedRoot))) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + doThrow(new CertificateExpiredException()).when(trustedRoot).checkValidity(); assertThatThrownBy( () -> RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( - List.of(trustedRoot, trustedRoot))) + List.of(trustedRoot))) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); } From 333d4edbe1530489b9d79c60cfa1dbc7b03b7b90 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:37:22 +1300 Subject: [PATCH 20/28] Validate PREPARING acquisition before retaining activation protections --- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 8 +- ...ivation_settlement_lifecycle_integrity.sql | 314 ++++++++++++++---- ...tionProtectionPostgresIntegrationTest.java | 161 +++++++++ .../repository/CharacterRepository.java | 3 +- ...eseededActorAssignmentIntegrationTest.java | 3 +- 6 files changed, 428 insertions(+), 63 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 64b7f6837d..d2f2c20577 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -338,6 +338,6 @@ Account retains admission and activation protection separately from the original The existing Account source-lock order remains canonical: source-key locks precede protection-row locks, and NOWAIT refuses a reversed or unavailable acquisition. Pending admission or activation blocks the existing source-hold, source-change and hosted-terms disclosure paths until the distinct protection has its exact immutable terminal settlement. Expiry, World receiving settlement, absence and an asserted outcome cannot release another protection. Settlement stores the complete original protection and exact terminal binding; these SQL checks validate integrity and do not authenticate the terminal producer. The owner obligations remain defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). -Forward [V1004 lifecycle integrity](../../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql) additionally requires a COMMITTED activation settlement to retain closed ACTIVE lifecycle evidence bound to the original PREPARING request and immutable owner values. Malformed or ambiguous lifecycle carriers retain the pending source-writer exclusion; exact ABORTED terminal handling remains separate. This storage validation does not authenticate World or activate the source path. Current proof and limits belong in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). +Forward [V1004 lifecycle integrity](../../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql) applies one complete closed lifecycle validator to PREPARING evidence before protection acquisition and ACTIVE evidence during COMMITTED settlement. Settlement also binds the retained PREPARING request and immutable owner values; acquisition cannot retain a malformed carrier which its matching COMMITTED result must reject. Malformed or ambiguous lifecycle carriers retain the pending source-writer exclusion; exact ABORTED terminal handling remains separate. This storage validation does not authenticate World or activate the source path. Current proof and limits belong in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. 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 be78b8ed5a..1b7594d438 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,7 +18,11 @@ The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca1 The subsequent Hosted/CLI correction on develop `18f8063306c2ddb4337646de50b73619915a0e25` executed 18 focused Account PostgreSQL cases with zero failures, errors or skips. Acquisition now rejects admission data that cannot satisfy immutable settlement bounds; committed activation fixtures run the acquisition, source-child and deferred-completeness guards. The proof includes the 256-source boundary, canonical Base64 and UTF-16 ordering, a complete activation tuple above 135,168 bytes, and settlement after lease expiry. Actual jOOQ generation, compilation, integration Checkstyle and SpotBugs, formatting and documentation checks passed. This corrects the bounded fixture proof; the older broad source-CI counts remain historical and do not qualify the changed SQL or establish genuine owner production. -The additional review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. +The acquisition/settlement alignment now applies one closed outer lifecycle validator to PREPARING acquisition and ACTIVE settlement, retaining opaque nested launch evidence exactly rather than duplicating its codec or authenticating World. Its final focused gate passes 22 physical PostgreSQL cases (18 admission and four activation), zero failures, errors or skips, in 1m29s: 40 malformed acquisition variants leave no protection/source rows or writer exclusion, while the 58 settlement negatives, retained V1003 upgrade/history/rows, valid ACTIVE and separate ABORTED release remain covered. The control-plane request bound reuses the existing UTF-16 helper. The first attempt failed before SQL in four Activation cases; one bounded retry established the intended red by accepting malformed PREPARING evidence. The subsequent green gate generated jOOQ and passed formatting, integration Checkstyle and SpotBugs. Migration-tip proof now checks all current resolved migrations and explicit V1003/V1004 presence while retaining the frozen 112-artifact parent; the isolated V1003-to-V1004 upgrade remains pinned. + +Exact-source cloud proof for the preceding published `02401d4df0276b04c7f0ff780441a050c4b72fc8` on develop `683c2a2b3417456a2eb5758401a9bc347e53e29a` passes 1,291 executed Account units (four additional defined cases skipped) and all 246 physical integration cases in Validation `38475212382`, job `115564246534`, JUnit artifact `11855135658`. Runtime `38475212357` executes both legacy WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK flows; its separate Smoke Gate fails on missing REST step metadata, with the tooling correction owned by Overseer. These results qualify that preceding SQL only, not this acquisition repair. The original failed local full run remains failed; newer exact-candidate CI and packaged proof remain required. + +The preceding review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. @@ -156,7 +160,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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. `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; genuine owner acquisition and authenticated terminal-settlement producers remain open. | +| `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. | | `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`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql index 2c0e791916..5d4a0ed361 100644 --- a/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql +++ b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql @@ -1,57 +1,35 @@ --- COMMITTED settlement must carry closed ACTIVE lifecycle evidence for the retained --- PREPARING observation. Keep V1003's terminal, outcome, source and request guards installed. +-- Validate closed PREPARING lifecycle evidence before acquiring a source protection, +-- and closed ACTIVE evidence before accepting COMMITTED settlement. Preserve V1003's +-- source/owner lock order, completeness, terminal, outcome and immutable binding fences. -- This integrity guard does not authenticate World or duplicate its nested launch-binding codec: --- launch binding and all immutable lifecycle values must remain exactly the retained owner values. +-- launch binding and all immutable lifecycle values remain exactly the retained owner values. -- [jooq ignore start] -CREATE FUNCTION account_ss_activation_settlement_lifecycle_guard() -RETURNS TRIGGER LANGUAGE plpgsql AS $$ +CREATE FUNCTION account_ss_activation_validate_lifecycle( + lifecycle_bytes BYTEA, + expected_status TEXT +) RETURNS JSONB LANGUAGE plpgsql IMMUTABLE STRICT AS $$ DECLARE - original account_start_session_activation_protections%ROWTYPE; - result_value JSONB; - lifecycle_base64 TEXT; - lifecycle_bytes BYTEA; lifecycle JSONB; - preparing JSONB; request_value JSONB; field_name TEXT; region RECORD; uuid_pattern CONSTANT TEXT := '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; nil_uuid CONSTANT TEXT := '00000000-0000-0000-0000-000000000000'; BEGIN - IF NEW.outcome <> 'COMMITTED' THEN - RETURN NEW; - END IF; - SELECT * INTO STRICT original FROM account_start_session_activation_protections - WHERE activation_protection_id = NEW.activation_protection_id; - result_value := convert_from(decode( - convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', - 'base64'), 'UTF8')::JSONB; - IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN - RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' - USING ERRCODE = '23514'; - END IF; - lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; - lifecycle_bytes := decode(lifecycle_base64, 'base64'); - IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') - IS DISTINCT FROM lifecycle_base64 THEN - RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' - USING ERRCODE = '23514'; - END IF; -- Check before JSONB normalizes duplicate keys, including duplicates in nested objects. IF NOT (convert_from(lifecycle_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN - RAISE EXCEPTION 'Committed activation lifecycle requires unique closed JSON object keys' + RAISE EXCEPTION 'Activation lifecycle requires unique closed JSON object keys' USING ERRCODE = '23514'; END IF; -- JSON preserves the number spelling that JSONB may normalize (for example 1e0). IF (convert_from(lifecycle_bytes, 'UTF8')::JSON->'request'->'schemaVersion')::TEXT IS DISTINCT FROM '1' THEN - RAISE EXCEPTION 'Committed activation lifecycle schemaVersion must be the integral JSON number 1' + RAISE EXCEPTION 'Activation lifecycle schemaVersion must be the integral JSON number 1' USING ERRCODE = '23514'; END IF; lifecycle := convert_from(lifecycle_bytes, 'UTF8')::JSONB; - preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' THEN - RAISE EXCEPTION 'Committed activation lifecycle must be a closed object' + RAISE EXCEPTION 'Activation lifecycle must be a closed object' USING ERRCODE = '23514'; END IF; IF (SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 12 @@ -60,27 +38,18 @@ BEGIN 'runtimeRoomInstanceId', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion', 'captureId', 'graphSha256', 'preparationInputDigest', 'operationalRegionAssignments']) OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' - OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' - OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM expected_status OR jsonb_typeof(lifecycle->'request') IS DISTINCT FROM 'object' OR jsonb_typeof(lifecycle->'startLocation') IS DISTINCT FROM 'object' OR jsonb_typeof(lifecycle->'operationalRegionAssignments') IS DISTINCT FROM 'object' THEN - RAISE EXCEPTION 'Committed activation lifecycle must be closed ACTIVE owner evidence' - USING ERRCODE = '23514'; - END IF; - -- Only status, counters and the read observation identity may change during activation. - IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] - IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] - OR (lifecycle->'request') - 'readRequestId' - IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN - RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + RAISE EXCEPTION 'Activation lifecycle must be closed owner evidence for the expected status' USING ERRCODE = '23514'; END IF; FOREACH field_name IN ARRAY ARRAY[ 'schema', 'launchBindingBytesBase64', 'runtimeRoomInstanceId', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion', 'captureId', 'graphSha256', 'preparationInputDigest'] LOOP IF jsonb_typeof(lifecycle->field_name) IS DISTINCT FROM 'string' THEN - RAISE EXCEPTION 'Committed activation lifecycle scalar must be a string: %', field_name + RAISE EXCEPTION 'Activation lifecycle scalar must be a string: %', field_name USING ERRCODE = '23514'; END IF; END LOOP; @@ -88,7 +57,7 @@ BEGIN IF lifecycle->>field_name !~ '^(0|[1-9][0-9]*)$' OR (lifecycle->>field_name)::NUMERIC > 9223372036854775807 OR (field_name <> 'rowVersion' AND (lifecycle->>field_name)::NUMERIC = 0) THEN - RAISE EXCEPTION 'Committed activation lifecycle counter is invalid: %', field_name + RAISE EXCEPTION 'Activation lifecycle counter is invalid: %', field_name USING ERRCODE = '23514'; END IF; END LOOP; @@ -99,7 +68,7 @@ BEGIN OR regexp_replace(encode(decode(lifecycle->>'launchBindingBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') IS DISTINCT FROM lifecycle->>'launchBindingBytesBase64' THEN - RAISE EXCEPTION 'Committed activation lifecycle identities or retained launch bytes are invalid' + RAISE EXCEPTION 'Activation lifecycle identities or retained launch bytes are invalid' USING ERRCODE = '23514'; END IF; request_value := lifecycle->'request'; @@ -114,7 +83,7 @@ BEGIN OR request_value->>'schemaVersion' IS DISTINCT FROM '1' OR request_value->'publicProduction' IS DISTINCT FROM 'true'::JSONB OR request_value->>'playableStateScope' IS DISTINCT FROM 'SHARED' THEN - RAISE EXCEPTION 'Committed activation lifecycle request must have the complete closed shape' + RAISE EXCEPTION 'Activation lifecycle request must have the complete closed shape' USING ERRCODE = '23514'; END IF; FOREACH field_name IN ARRAY ARRAY[ @@ -123,7 +92,7 @@ BEGIN 'controlPlaneRequestId', 'canonicalVersionId', 'expectedDescriptorRequestDigest', 'expectedDescriptorResultDigest', 'expectedReleaseAttestationDigest'] LOOP IF jsonb_typeof(request_value->field_name) IS DISTINCT FROM 'string' THEN - RAISE EXCEPTION 'Committed activation lifecycle request scalar must be a string: %', field_name + RAISE EXCEPTION 'Activation lifecycle request scalar must be a string: %', field_name USING ERRCODE = '23514'; END IF; END LOOP; @@ -131,7 +100,7 @@ BEGIN 'readRequestId', 'canonicalTenantId', 'canonicalGameInstanceId', 'playableStateNamespaceId', 'canonicalVersionId'] LOOP IF request_value->>field_name !~ uuid_pattern OR request_value->>field_name = nil_uuid THEN - RAISE EXCEPTION 'Committed activation lifecycle request UUID is invalid: %', field_name + RAISE EXCEPTION 'Activation lifecycle request UUID is invalid: %', field_name USING ERRCODE = '23514'; END IF; END LOOP; @@ -139,7 +108,7 @@ BEGIN 'expectedDescriptorRequestDigest', 'expectedDescriptorResultDigest', 'expectedReleaseAttestationDigest'] LOOP IF request_value->>field_name !~ '^sha256:[0-9a-f]{64}$' THEN - RAISE EXCEPTION 'Committed activation lifecycle request digest is invalid: %', field_name + RAISE EXCEPTION 'Activation lifecycle request digest is invalid: %', field_name USING ERRCODE = '23514'; END IF; END LOOP; @@ -147,28 +116,29 @@ BEGIN OR request_value->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' OR octet_length(request_value->>'worldSlug') NOT BETWEEN 1 AND 120 OR request_value->>'worldSlug' !~ '^[a-z0-9]+(-[a-z0-9]+)*$' - OR length(request_value->>'controlPlaneRequestId') NOT BETWEEN 1 AND 128 + OR cardinality(account_publication_authorization_source_sort_key( + request_value->>'controlPlaneRequestId')) NOT BETWEEN 1 AND 128 OR request_value->>'controlPlaneRequestId' ~ '^[[:space:]]*$' THEN - RAISE EXCEPTION 'Committed activation lifecycle request text is invalid' + RAISE EXCEPTION 'Activation lifecycle request text is invalid' USING ERRCODE = '23514'; END IF; IF (SELECT count(*) FROM jsonb_object_keys(lifecycle->'startLocation')) <> 3 OR NOT (lifecycle->'startLocation' ?& ARRAY['tenantId', 'versionId', 'roomTemplateId']) THEN - RAISE EXCEPTION 'Committed activation lifecycle start location must be closed' + RAISE EXCEPTION 'Activation lifecycle start location must be closed' USING ERRCODE = '23514'; END IF; FOREACH field_name IN ARRAY ARRAY['tenantId', 'versionId', 'roomTemplateId'] LOOP IF jsonb_typeof(lifecycle->'startLocation'->field_name) IS DISTINCT FROM 'string' OR lifecycle->'startLocation'->>field_name !~ uuid_pattern OR lifecycle->'startLocation'->>field_name = nil_uuid THEN - RAISE EXCEPTION 'Committed activation lifecycle start location UUID is invalid: %', field_name + RAISE EXCEPTION 'Activation lifecycle start location UUID is invalid: %', field_name USING ERRCODE = '23514'; END IF; END LOOP; IF (SELECT count(*) FROM jsonb_object_keys(lifecycle->'operationalRegionAssignments')) = 0 OR (SELECT count(*) FROM jsonb_each(lifecycle->'operationalRegionAssignments')) <> (SELECT count(DISTINCT value) FROM jsonb_each(lifecycle->'operationalRegionAssignments')) THEN - RAISE EXCEPTION 'Committed activation lifecycle requires distinct operational region assignments' + RAISE EXCEPTION 'Activation lifecycle requires distinct operational region assignments' USING ERRCODE = '23514'; END IF; FOR region IN SELECT key, value FROM jsonb_each(lifecycle->'operationalRegionAssignments') LOOP @@ -176,10 +146,240 @@ BEGIN OR jsonb_typeof(region.value) IS DISTINCT FROM 'string' OR region.value #>> '{}' !~ uuid_pattern OR region.value #>> '{}' = nil_uuid OR region.key = region.value #>> '{}' THEN - RAISE EXCEPTION 'Committed activation lifecycle region assignment is invalid' + RAISE EXCEPTION 'Activation lifecycle region assignment is invalid' USING ERRCODE = '23514'; END IF; END LOOP; + RETURN lifecycle; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; + +CREATE OR REPLACE FUNCTION account_ss_activation_assert_current( + request_bytes BYTEA, + operation_bytes BYTEA, + operation_digest TEXT, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + retained account_start_session_activation_protections%ROWTYPE; + snapshot_value JSONB; + request_value JSONB; + tuple_value JSONB; + projection_value JSONB; + preparing_value JSONB; + preparing_request JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + tuple_bytes BYTEA; + projection_bytes BYTEA; + preparing_bytes BYTEA; + control_request_id TEXT; + requested_participation_id UUID; + keys TEXT[]; + retained_found BOOLEAN := FALSE; +BEGIN + IF octet_length(request_bytes) NOT BETWEEN 1 AND 150994944 + OR octet_length(operation_bytes) NOT BETWEEN 1 AND 150994944 + OR operation_digest IS DISTINCT FROM 'sha256:' || encode(sha256(operation_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession activation request or operation identity is invalid' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(request_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 12 + OR NOT (request_value ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' THEN + RAISE EXCEPTION 'Original StartSession activation request has an unsupported shape' + USING ERRCODE = '23514'; + END IF; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + PERFORM account_ss_activation_validate_lifecycle(preparing_bytes, 'PREPARING'); + tuple_value := convert_from(tuple_bytes, 'UTF8')::JSONB; + control_request_id := tuple_value->>'controlPlaneRequestId'; + requested_participation_id := (request_value->>'accountWorldParticipationId')::UUID; + + -- Source-key locks are acquired in the canonical V129 order before any retained owner, + -- World or activation-protection row is locked. + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id THEN + RAISE EXCEPTION 'Activation protection requires the exact original Account source snapshot' + USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE account_start_session_world_participations.participation_id = requested_participation_id + FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = world_parent.participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO retained FROM account_start_session_activation_protections + WHERE account_start_session_activation_protections.control_plane_request_id = control_request_id + FOR UPDATE NOWAIT; + retained_found := FOUND; + + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + projection_value := convert_from(projection_bytes, 'UTF8')::JSONB; + IF request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM observation.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM observation.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM observation.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(observation.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM world_parent.participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM world_parent.participation_fence::TEXT + OR world_parent.control_plane_request_id IS DISTINCT FROM control_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR observation.target_namespace IS DISTINCT FROM world_parent.target_namespace + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = world_parent.participation_id + AND settlement.outcome = 'COMMITTED') + OR preparing_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing_value->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing_request->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id + OR preparing_request->>'targetNamespace' IS DISTINCT FROM world_parent.target_namespace + OR preparing_request->>'canonicalTenantId' IS DISTINCT FROM world_parent.canonical_tenant_id::TEXT + OR preparing_request->>'canonicalGameInstanceId' IS DISTINCT FROM world_parent.canonical_game_instance_id::TEXT + OR capture.source_version <= 0 OR capture.source_fence <= 0 THEN + RAISE EXCEPTION 'Activation protection differs from committed original World preparation or attempt' + USING ERRCODE = '23514'; + END IF; + + -- Retain the original Account issuance/redemption tuple and complete projection exactly. + IF capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_snapshot_bytes), 'hex') + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR projection_bytes IS DISTINCT FROM tuple_bytes + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT + OR capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection differs from original Account redemption or capture' + USING ERRCODE = '23514'; + END IF; + + IF retained_found AND ( + retained.operation_identity_bytes IS DISTINCT FROM operation_bytes + OR retained.operation_identity_digest IS DISTINCT FROM operation_digest + OR retained.account_world_participation_id IS DISTINCT FROM world_parent.participation_id + OR retained.account_world_participation_fence IS DISTINCT FROM world_parent.participation_fence) THEN + RAISE EXCEPTION 'Original StartSession activation protection conflicts with its immutable binding' + USING ERRCODE = '23514'; + END IF; + + -- The typed Common carrier validates the closed Game Session STARTING result and exact + -- World PREPARING evidence. SQL independently checks finite original authority only after + -- all canonical source and owner/protection row locks have completed. + IF observation.original_lease_expires_at IS DISTINCT FROM + (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR observation.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession activation protection lease is stale or expired' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id) + <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Activation protection has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id + AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Activation protection source child differs from original capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + lifecycle := account_ss_activation_validate_lifecycle(lifecycle_bytes, 'ACTIVE'); + preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; + IF preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' THEN + RAISE EXCEPTION 'Committed activation requires retained PREPARING owner evidence' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; RETURN NEW; EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range OR invalid_parameter_value THEN diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 8fecbdebeb..53ec58e783 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -477,6 +477,167 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .contains("account_start_session_activation_protection_settlements"); } + @Test + void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(current.requestBytes()); + byte[] preparingBytes = + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")); + java.util.List malformed = new java.util.ArrayList<>(); + Map extraOuter = readJson(preparingBytes); + extraOuter.put("extra", true); + malformed.add(jsonBytes(extraOuter)); + for (String field : + new String[] { + "launchBindingBytesBase64", + "startLocation", + "runtimeRoomInstanceId", + "lifecycleEpoch", + "rowVersion", + "captureId", + "graphSha256", + "preparationInputDigest", + "operationalRegionAssignments" + }) { + Map missing = readJson(preparingBytes); + missing.remove(field); + malformed.add(jsonBytes(missing)); + Map wrongType = readJson(preparingBytes); + wrongType.put(field, 1); + malformed.add(jsonBytes(wrongType)); + } + for (Map.Entry change : + Map.ofEntries( + Map.entry("runtimeRoomInstanceId", "0"), + Map.entry("lifecycleEpoch", "01"), + Map.entry("rowVersion", "9223372036854775808"), + Map.entry("captureId", "00000000-0000-0000-0000-000000000000"), + Map.entry("graphSha256", "invalid"), + Map.entry("preparationInputDigest", "invalid"), + Map.entry("launchBindingBytesBase64", "%%%"), + Map.entry("startLocation", Map.of()), + Map.entry("operationalRegionAssignments", Map.of())) + .entrySet()) { + Map changed = readJson(preparingBytes); + changed.put(change.getKey(), change.getValue()); + malformed.add(jsonBytes(changed)); + } + for (Map.Entry change : + Map.ofEntries( + Map.entry("extra", true), + Map.entry("publicProduction", false), + Map.entry("playableStateScope", "ISOLATED"), + Map.entry("schemaVersion", 2), + Map.entry("readRequestId", "00000000-0000-0000-0000-000000000000"), + Map.entry("worldSlug", "INVALID"), + Map.entry("expectedDescriptorRequestDigest", "invalid"), + Map.entry("canonicalVersionId", 1)) + .entrySet()) { + Map changed = readJson(preparingBytes); + @SuppressWarnings("unchecked") + Map changedRequest = (Map) changed.get("request"); + changedRequest.put(change.getKey(), change.getValue()); + malformed.add(jsonBytes(changed)); + } + String preparingJson = new String(preparingBytes, StandardCharsets.UTF_8); + for (String value : + new String[] { + preparingJson.replace("\"schemaVersion\":1", "\"schemaVersion\":1e0"), + preparingJson.replace("\"schemaVersion\":1", "\"schemaVersion\":1e+0"), + preparingJson.replace("\"schemaVersion\":1", "\"schemaVersion\":0,\"schemaVersion\":1") + }) { + malformed.add(bytes(value)); + } + Map oversizedRequestId = readJson(preparingBytes); + @SuppressWarnings("unchecked") + Map oversizedLifecycleRequest = + (Map) oversizedRequestId.get("request"); + // 128 Unicode code points occupy 129 Java UTF-16 units. + oversizedLifecycleRequest.put("controlPlaneRequestId", "a".repeat(127) + "\uD83D\uDE00"); + byte[] oversizedRequestIdBytes = jsonBytes(oversizedRequestId); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_validate_lifecycle(?, 'PREPARING')", + oversizedRequestIdBytes))) + .hasMessageContaining("Activation lifecycle request text is invalid"); + malformed.add(oversizedRequestIdBytes); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_world_participation_sources ORDER BY source_key LIMIT 1") + .get(0, String.class); + for (byte[] invalidPreparing : malformed) { + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(invalidPreparing)) + .isInstanceOf(IllegalArgumentException.class); + Map changedRequest = readJson(current.requestBytes()); + changedRequest.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(invalidPreparing)); + CurrentnessCase changed = + new CurrentnessCase( + jsonBytes(changedRequest), + current.operationIdentityBytes(), + current.operationIdentityDigest(), + current.ownerAttemptId(), + current.expiryText()); + assertThatThrownBy(() -> acquireProtection(fixture, changed)) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) + postgresFailure = postgresFailure.getCause(); + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); + assertThat( + fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_sources"))) + .isZero(); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + } + acquireProtection(fixture, current); + assertThat(fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isEqualTo(1); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + @Test void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() throws Exception { Fixture fixture = fixture(); 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 bcfe93da5d..bcb6ccf6ef 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 @@ -272,7 +272,8 @@ public long countQuarantinedByTenantId(Long tenantId) { CHARACTERS .TENANT_ID .eq(tenantId) - .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.QUARANTINED.name()))); + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.QUARANTINED.name())) + .and(CHARACTERS.TENANT_UUID.isNull())); } /** diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index a24109b6a2..62851cfa7b 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -832,8 +832,7 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn entityTenantRowId, namespaceUuid.toString(), "Canonical Actor")) .isEmpty(); assertThat(characterRepository.countByTenantId(entityTenantRowId)).isEqualTo(2); - assertThat(characterRepository.countQuarantinedByTenantId(entityTenantRowId)) - .isEqualTo(quarantined ? 3 : 2); + assertThat(characterRepository.countQuarantinedByTenantId(entityTenantRowId)).isEqualTo(2); assertThat(inventoryEntryRepository.countByCharacterTenantId(entityTenantRowId)).isEqualTo(1); assertThat(characterEquipmentRepository.countByCharacterTenantId(entityTenantRowId)) .isEqualTo(1); From af5a191e30704d37cd296d0c7bfce6d1ad83620d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:54:59 +1300 Subject: [PATCH 21/28] test(entity): assert retained identity constraint failures precisely --- .../RetainedActorIdentityIntegrationTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 142a3d42a4..45a9ba416b 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 @@ -242,12 +242,14 @@ void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { "OWNER_PROVENANCE_MISSING", accountId, tenantId)) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(org.springframework.dao.DuplicateKeyException.class) + .hasMessageContaining("ux_characters_character_uuid"); assertThatThrownBy( () -> insertNamespace( tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(org.springframework.dao.DuplicateKeyException.class) + .hasMessageContaining("pk_entity_playable_state_namespace_scopes"); } private List storedActorUuids( From e5fee409d7a26e3e4697ffdb6cfe025ad8f908bb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:32:07 +1300 Subject: [PATCH 22/28] fix: preserve activation counters and exact migration parent validation --- .github/workflows/ci.yml | 17 +-- .../account-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 12 +- .../player-access-and-session.md | 2 + .../tests/pr-retarget-workflow-contract.sh | 85 +++++++++++++-- dev-tools/validation/check-flyway-versions.py | 5 +- ...ettlement_monotonic_lifecycle_counters.sql | 59 ++++++++++ ...tionProtectionPostgresIntegrationTest.java | 103 ++++++++++++++++-- .../ActorActiveConditionRepository.java | 29 +++-- .../ActorResourceStateRepository.java | 20 ++-- .../repository/CharacterFriendRepository.java | 20 ++-- .../repository/CharacterRepository.java | 7 ++ 12 files changed, 292 insertions(+), 69 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e9a5f8d41..256f5b66f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -557,20 +557,21 @@ jobs: - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - - name: Fetch manual Flyway parent when needed - if: ${{ github.event_name == 'workflow_dispatch' }} + - name: Fetch exact Flyway parent env: - FLYWAY_BASE_SHA: ${{ inputs.flyway_base_sha }} + FLYWAY_BASE_SHA: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + FLYWAY_EVENT_NAME: ${{ github.event_name }} run: | - if [[ ! "$FLYWAY_BASE_SHA" =~ ^[[:xdigit:]]{40}$ ]]; then - echo "workflow_dispatch requires a full immutable 40-character Flyway base SHA" >&2 + if [[ "$FLYWAY_BASE_SHA" == "0000000000000000000000000000000000000000" && "$FLYWAY_EVENT_NAME" != "workflow_dispatch" ]]; then + exit 0 + fi + if [[ ! "$FLYWAY_BASE_SHA" =~ ^[[:xdigit:]]{40}$ || "$FLYWAY_BASE_SHA" == "0000000000000000000000000000000000000000" ]]; then + echo "Flyway parent requires a full nonzero immutable 40-character SHA" >&2 exit 1 fi if ! git cat-file -e "${FLYWAY_BASE_SHA}^{commit}" 2>/dev/null; then - git fetch --no-tags origin "$FLYWAY_BASE_SHA" + git fetch --no-tags --depth=1 origin "$FLYWAY_BASE_SHA" fi resolved_sha="$(git rev-parse --verify "${FLYWAY_BASE_SHA}^{commit}")" if [[ "${resolved_sha,,}" != "${FLYWAY_BASE_SHA,,}" ]]; then diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d2f2c20577..2b64a1a099 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -340,4 +340,6 @@ The existing Account source-lock order remains canonical: source-key locks prece Forward [V1004 lifecycle integrity](../../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql) applies one complete closed lifecycle validator to PREPARING evidence before protection acquisition and ACTIVE evidence during COMMITTED settlement. Settlement also binds the retained PREPARING request and immutable owner values; acquisition cannot retain a malformed carrier which its matching COMMITTED result must reject. Malformed or ambiguous lifecycle carriers retain the pending source-writer exclusion; exact ABORTED terminal handling remains separate. This storage validation does not authenticate World or activate the source path. Current proof and limits belong in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). +Forward [V1004.1](../../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql) also rejects a COMMITTED ACTIVE lifecycle whose `lifecycleEpoch` or `rowVersion` is lower than the retained PREPARING counter. Equal or increased counters remain valid; malformed values and other lifecycle binding checks keep V1004's behavior. This remains Account storage integrity validation and does not authenticate World or activate the source path. + V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 635f976340..364c301592 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -254,6 +254,12 @@ Entry format: - Current status: local transactional implementation is prepared; installed-selector promotion and live rollout verification remain pending with the owning orchestrator. - Reconsideration trigger: verify concurrent metadata batches after coordinated version-matched selector promotion. -- `2026-10-14`: Review-period reset recovery verified after coordinated promotion - - Outcome: [#3213](https://github.com/benhook1013/FireMUD/pull/3213) merged at `f4219551ad30c52933f184d6bf4aabb4373ef9c7`; all installed public selectors use writer build 11. Old reset writers drained at native command boundaries before promotion. Gameplay preserved the previous 58 applied keys and completed the remaining 24 serial resets in approximately 0.14–0.24 seconds per native call. Independent native-store readback verified all 82 unique periods across 41 open PRs, complete baselines, the requested defaults and no retained live stop in scope. - - Limit: this rollout used serialized metadata calls; it does not claim a new live concurrent-reset experiment. Existing provider findings, proof and historical review attribution remain preserved. +- `2026-10-14`: Transfer terminal-owned work at a native command boundary + - Context: a replacement subagent could not attach to the main agent’s existing execution session; the tools returned an unknown process ID even though the main agent could still observe its running batch. + - Expected pattern: keep one execution owner, finish the current native command without cancellation, then resume only the missing stable operation keys from the canonical store in the new owner’s terminal. An execution-session ID does not transfer process ownership across agent contexts. Use the same boundary to drain incompatible database writers before coordinated selector promotion. + - Evidence limits: completion counts and rollout timings remain in the owning controller job. This handoff does not replace the separate concurrent-reset reconsideration trigger above. + +- `2026-10-14`: Verify user-visible rendering against installed controller input + - Observation: Root deployed the numeric review-limit renderer before the matching controller fields were installed. Formatter tests passed, but interim live queue rows showed `Limits not reported`. + - Expected pattern: pair rendering changes with the version-matched controller input and verify the actual endpoint before claiming the related user-facing outcome is complete. This is a reusable verification lesson, not an additional approval gate or lifecycle policy. + - Recovery: coordinated controller promotion and actual-endpoint verification restored numeric limits; the owning controller job retains the rollout details. 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 1b7594d438..e7eb574002 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,6 +24,8 @@ Exact-source cloud proof for the preceding published `02401d4df0276b04c7f0ff7804 The preceding review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. +Forward V1004.1 rejects a COMMITTED settlement with a regressing World `lifecycleEpoch` or `rowVersion`. The corrected focused run passed all 22 physical PostgreSQL cases with zero failures, errors or skips in 1m40s, including the pinned V1003-to-V1004 historical upgrade, a separate V1004-to-V1004.1 comparison of prior migration ranks/checksums and retained pending-protection/source bytes and `xmin`, both counter decreases retaining writer exclusion, and a valid increased epoch with equal row version. The initial consolidated run failed one new fixture assertion because its proposed row-version decrease was equal to the retained zero; that failed result remains retained. The fixture now starts that case at row version one without changing the guard or other fixture defaults. Account integration static and formatting checks pass; jOOQ generation and the broader Account static/unit checks passed in the initial invocation (1,295 unit cases, four existing filesystem skips). Entity checks also passed with 237 unit and 28 integration cases. These are controlled storage fixtures, not authenticated World production or activation; published-head CI remains separate. + The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. ### Entity character-creation denial diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 7bceba02e6..3fd5af5d10 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -386,9 +386,12 @@ for filename in ("ci.yml", "security.yml", "license-scan.yml", "codeql.yml"): raise SystemExit(f"{filename} must retain an empty manual dispatch") PYTHON -# Manual CI dispatch must pass and fetch its exact immutable Flyway parent. +# Every CI event must fetch its exact immutable Flyway parent with shallow history. python3 - "$ci_path" <<'PYTHON' +import os +import subprocess import sys +import tempfile from pathlib import Path import yaml @@ -396,19 +399,29 @@ import yaml workflow = yaml.load(Path(sys.argv[1]).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) job = workflow["jobs"]["flyway-migration-sanity-checks"] steps = job["steps"] -fetch_steps = [step for step in steps if step.get("name") == "Fetch manual Flyway parent when needed"] +fetch_steps = [step for step in steps if step.get("name") == "Fetch exact Flyway parent"] if len(fetch_steps) != 1: - raise SystemExit("CI must have exactly one manual Flyway parent fetch step") + raise SystemExit("CI must have exactly one exact Flyway parent fetch step") fetch = fetch_steps[0] -if fetch.get("if") != "${{ github.event_name == 'workflow_dispatch' }}": - raise SystemExit("Flyway parent fetching must run only for manual dispatch") -if fetch.get("env") != {"FLYWAY_BASE_SHA": "${{ inputs.flyway_base_sha }}"}: - raise SystemExit("Flyway parent fetch must use the configured manual input") +if "if" in fetch: + raise SystemExit("Flyway parent fetching must cover every event") +expected_base = ( + "${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha " + "|| github.event_name == 'pull_request' && github.event.pull_request.base.sha " + "|| github.event.before }}" +) +if fetch.get("env") != {"FLYWAY_BASE_SHA": expected_base, "FLYWAY_EVENT_NAME": "${{ github.event_name }}"}: + raise SystemExit("Flyway fetch and checker must use the same immutable event parent") +checkout_steps = [step for step in steps if str(step.get("uses", "")).startswith("actions/checkout@")] +if len(checkout_steps) != 1 or "fetch-depth" in checkout_steps[0].get("with", {}): + raise SystemExit("Flyway parent fetch must retain the default shallow checkout") fetch_script = fetch.get("run", "") for required in ( + '"$FLYWAY_EVENT_NAME" != "workflow_dispatch"', + '"$FLYWAY_BASE_SHA" == "0000000000000000000000000000000000000000"', "^[[:xdigit:]]{40}$", 'git cat-file -e "${FLYWAY_BASE_SHA}^{commit}"', - 'git fetch --no-tags origin "$FLYWAY_BASE_SHA"', + 'git fetch --no-tags --depth=1 origin "$FLYWAY_BASE_SHA"', 'git rev-parse --verify "${FLYWAY_BASE_SHA}^{commit}"', ): if required not in fetch_script: @@ -424,6 +437,62 @@ expected_base = ( ) if check_steps[0].get("env", {}).get("FIREMUD_FLYWAY_BASE_REF") != expected_base: raise SystemExit("Flyway version check must preserve dispatch, PR-base, and push-before parent selection") +# Exercise the actual YAML fetch script against a shallow checkout, rather than +# relying only on static command spelling or the checkout action's defaults. +checker = Path(sys.argv[1]).resolve().parents[2] / "dev-tools/validation/check-flyway-versions.py" +with tempfile.TemporaryDirectory(prefix="firemud-flyway-shallow-") as temporary: + fixture = Path(temporary) / "source" + fixture.mkdir() + def git_at(directory, *arguments): + return subprocess.run(["git", *arguments], cwd=directory, check=True, + capture_output=True, text=True).stdout.strip() + git_at(fixture, "init", "-q") + migration = fixture / "services/example-service/src/main/resources/db/migration" + migration.mkdir(parents=True) + (fixture / "services/example-service/build.gradle.kts").write_text("dependencies {}\n") + (migration / "V1__base.sql").write_text("-- base fixture\n") + git_at(fixture, "add", ".") + git_at(fixture, "-c", "user.name=Flyway fixture", "-c", "user.email=fixture@example.invalid", + "commit", "-qm", "base") + parent = git_at(fixture, "rev-parse", "HEAD") + (migration / "V2__forward.sql").write_text("-- forward fixture\n") + git_at(fixture, "add", ".") + git_at(fixture, "-c", "user.name=Flyway fixture", "-c", "user.email=fixture@example.invalid", + "commit", "-qm", "forward") + child = git_at(fixture, "rev-parse", "HEAD") + checkout = Path(temporary) / "checkout" + subprocess.run(["git", "clone", "--depth=1", fixture.as_uri(), str(checkout)], + check=True, capture_output=True, text=True) + if git_at(checkout, "rev-parse", "HEAD") != child: + raise SystemExit("shallow fixture selected the wrong immutable child") + environment = dict(os.environ) + for name in ("GITHUB_EVENT_PATH", "GITHUB_EVENT_NAME", "FIREMUD_FLYWAY_BASE_REF"): + environment.pop(name, None) + command = [sys.executable, str(checker), "--root", str(checkout), "--base-ref", parent] + missing = subprocess.run(command, env=environment, capture_output=True, text=True) + if missing.returncode == 0 or "immutable receiving parent commit is unavailable" not in missing.stderr: + raise SystemExit(f"shallow checkout did not demonstrate missing parent: {missing.stdout} {missing.stderr}") + for event_name in ("pull_request", "push", "workflow_dispatch"): + environment.update(FLYWAY_BASE_SHA=parent, FLYWAY_EVENT_NAME=event_name) + fetched = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, + env=environment, capture_output=True, text=True) + if fetched.returncode or git_at(checkout, "rev-parse", parent + "^{commit}") != parent: + raise SystemExit(f"exact parent fetch failed for {event_name}: {fetched.stderr}") + available = subprocess.run(command, env=environment, capture_output=True, text=True) + if available.returncode: + raise SystemExit(f"checker rejected exact fetched parent: {available.stdout} {available.stderr}") + environment.update(FLYWAY_BASE_SHA="0" * 40, FLYWAY_EVENT_NAME="push") + sentinel = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, + env=environment, capture_output=True, text=True) + if sentinel.returncode: + raise SystemExit("new-branch sentinel must skip exact fetching") + environment["FLYWAY_EVENT_NAME"] = "workflow_dispatch" + sentinel = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, + env=environment, capture_output=True, text=True) + if sentinel.returncode == 0: + raise SystemExit("manual dispatch must reject the zero parent sentinel") + print("Shallow Flyway parent refusal, exact immutable fetch and event sentinel proof passed") + PYTHON # Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index ff1362473a..7154ac45d9 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -316,6 +316,8 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str event_path = Path(tmp) / "event.json" sha = "1" * 40 for event, expected in [({"pull_request": {"base": {"sha": sha}}}, sha), + ({"pull_request": {"base": None}}, None), + ({"pull_request": {"base": "invalid"}}, None), ({"before": sha}, sha), ({"before": "0" * 40}, None), ({}, None)]: event_path.write_text(json.dumps(event), encoding="utf-8") if event_base_ref(str(event_path)) != expected: @@ -375,7 +377,8 @@ def event_base_ref(event_path: str | None) -> str | None: event = json.loads(Path(event_path).read_text(encoding="utf-8")) pull_request = event.get("pull_request") if isinstance(pull_request, dict): - return pull_request.get("base", {}).get("sha") + base = pull_request.get("base") + return base.get("sha") if isinstance(base, dict) else None inputs = event.get("inputs") if isinstance(inputs, dict): return inputs.get("flyway_base_sha") diff --git a/services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql b/services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql new file mode 100644 index 0000000000..dd40ebe6bc --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql @@ -0,0 +1,59 @@ +-- Preserve V1004's closed ACTIVE lifecycle validation while requiring World-owned counters +-- to advance monotonically from the retained PREPARING evidence. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + lifecycle := account_ss_activation_validate_lifecycle(lifecycle_bytes, 'ACTIVE'); + preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; + IF preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' THEN + RAISE EXCEPTION 'Committed activation requires retained PREPARING owner evidence' + USING ERRCODE = '23514'; + END IF; + IF (lifecycle->>'lifecycleEpoch')::NUMERIC < (preparing->>'lifecycleEpoch')::NUMERIC + OR (lifecycle->>'rowVersion')::NUMERIC < (preparing->>'rowVersion')::NUMERIC THEN + RAISE EXCEPTION 'Committed activation lifecycle counters cannot regress' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Committed activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 53ec58e783..dda22d05b2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -38,10 +38,10 @@ import tools.jackson.databind.json.JsonMapper; /** - * Runs V1003/V1004 against the actual Account PostgreSQL schema and assembled source-writer guard. - * The integrity and currentness fixtures seed related owner rows with upstream producer triggers - * disabled. Protection acquisition, child completeness, settlement and source-writer guards remain - * enabled; they prove SQL currentness/exclusion/immutability only, not authenticated + * Runs V1003/V1004/V1004.1 against the actual Account PostgreSQL schema and assembled source-writer + * guard. The integrity and currentness fixtures seed related owner rows with upstream producer + * triggers disabled. Protection acquisition, child completeness, settlement and source-writer + * guards remain enabled; they prove SQL currentness/exclusion/immutability only, not authenticated * activation-protection production. */ @Testcontainers(disabledWithoutDocker = true) @@ -55,7 +55,7 @@ class AccountStartSessionActivationProtectionPostgresIntegrationTest { @Test void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() throws Exception { Fixture fixture = fixture("1003"); - CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(10), 135500); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(10), 135500, 1L); byte[] requestBinding = current.requestBytes(); Map request = readJson(requestBinding); UUID activationRequestId = UUID.fromString((String) request.get("worldActivationRequestId")); @@ -138,10 +138,10 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro + "WHERE version IS NOT NULL AND version <> '1004' ORDER BY installed_rank"; var installedHistory = fixture.dsl().fetch(retainedHistoryQuery).getValues(0, String.class); String protectionRowsQuery = - "SELECT row_to_json(p)::TEXT FROM " + "SELECT jsonb_build_object('row', to_jsonb(p), 'xmin', p.xmin::TEXT)::TEXT FROM " + "account_start_session_activation_protections p ORDER BY activation_protection_id"; String sourceRowsQuery = - "SELECT row_to_json(s)::TEXT FROM " + "SELECT jsonb_build_object('row', to_jsonb(s), 'xmin', s.xmin::TEXT)::TEXT FROM " + "account_start_session_activation_protection_sources s ORDER BY activation_protection_id, source_key"; var pendingRows = fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class); var retainedSources = fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class); @@ -172,6 +172,29 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .get(0, String.class)) .isNotNull(); + String preCounterUpgradeHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.1' ORDER BY installed_rank"; + var preCounterUpgradeHistory = + fixture.dsl().fetch(preCounterUpgradeHistoryQuery).getValues(0, String.class); + Flyway monotonicUpgrade = activationFlyway(fixture.dataSource(), "1004.1"); + assertThat(monotonicUpgrade.migrate().migrationsExecuted).isEqualTo(1); + monotonicUpgrade.validate(); + assertThat(fixture.dsl().fetch(preCounterUpgradeHistoryQuery).getValues(0, String.class)) + .isEqualTo(preCounterUpgradeHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + fixture .dsl() .fetch( @@ -318,6 +341,44 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .hasMessageContaining("Original StartSession activation protection remains pending"); } + for (Map.Entry regressingCounter : + Map.of("lifecycleEpoch", "2", "rowVersion", "0").entrySet()) { + String assertionDescription = + "Committed ACTIVE lifecycle must reject a decrease in " + regressingCounter.getKey(); + Map regressingLifecycle = readJson(activeBytes); + regressingLifecycle.put(regressingCounter.getKey(), regressingCounter.getValue()); + Map regressingResult = readJson(activationResultBytes); + regressingResult.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(jsonBytes(regressingLifecycle))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(regressingResult), + "COMMITTED", + assertionDescription); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + Map invalidTerminalCode = readJson(activationResultBytes); invalidTerminalCode.put("terminalCode", "FENCED_ABORT"); assertSettlementInsertRejected( @@ -803,6 +864,26 @@ private static void assertSettlementInsertRejected( byte[] protectionEvidenceBytes, byte[] activationResultBytes, String outcome) { + assertSettlementInsertRejected( + fixture, + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes, + outcome, + "Invalid activation settlement must be rejected"); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes, + String outcome, + String assertionDescription) { byte[] terminalBytes = terminalBytes( protectionId, @@ -835,6 +916,7 @@ private static void assertSettlementInsertRejected( terminalBytes, "terminal_digest", "sha256:" + hash(terminalBytes)))) + .as(assertionDescription) .isInstanceOf(RuntimeException.class) .satisfies( failure -> { @@ -990,6 +1072,11 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original private static CurrentnessCase currentnessCase( Fixture fixture, Instant originalLease, int padding) throws Exception { + return currentnessCase(fixture, originalLease, padding, 0L); + } + + private static CurrentnessCase currentnessCase( + Fixture fixture, Instant originalLease, int padding, long rowVersion) throws Exception { WorldCanonicalInstanceLifecycleEvidence lifecycle = AuthoringFixtures.lifecycleEvidence("PREPARING", 3L); UUID tenantId = lifecycle.request().canonicalTenantId(); @@ -1094,7 +1181,7 @@ private static CurrentnessCase currentnessCase( lifecycle.runtimeRoomInstanceId(), "PREPARING", lifecycle.lifecycleEpoch(), - lifecycle.rowVersion(), + rowVersion, lifecycle.captureId(), lifecycle.graphSha256(), preparationDigest, 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 5b4c3aceb8..cfdb6aad1a 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,16 +2,13 @@ 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; import java.util.List; import java.util.Optional; import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; -import org.jooq.Condition; import org.jooq.DSLContext; -import org.jooq.Field; import org.jooq.Record; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @@ -36,7 +33,8 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) - .and(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID)) + .and( + CharacterRepository.legacyCharacterExists(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID)) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -66,7 +64,9 @@ public List findActiveForCharacter( .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId)) - .and(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) .limit(1) .fetchOne(this::toEntity)); @@ -103,7 +103,9 @@ public ActorActiveCondition save(ActorActiveCondition entity) { DSL.val(entity.getEffectPayloadJson()), DSL.val(toOffsetDateTime(entity.getCreatedAt())), DSL.val(toOffsetDateTime(entity.getUpdatedAt()))) - .where(legacyCharacter(DSL.val(entity.getCharacterId())))) + .where( + CharacterRepository.legacyCharacterExists( + DSL.val(entity.getCharacterId())))) .returningResult(ACTOR_ACTIVE_CONDITIONS.ID) .fetchOne(ACTOR_ACTIVE_CONDITIONS.ID); if (id == null) { @@ -127,7 +129,9 @@ public ActorActiveCondition save(ActorActiveCondition entity) { ACTOR_ACTIVE_CONDITIONS .ID .eq(entity.getId()) - .and(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .execute(); if (updated != 1) { throw new IllegalStateException("Legacy condition row is unavailable"); @@ -143,17 +147,12 @@ public int deleteExpired(Instant now) { .EXPIRES_AT .isNotNull() .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now))) - .and(legacyCharacter(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .execute(); } - private static Condition legacyCharacter(Field characterId) { - return DSL.exists( - DSL.selectOne() - .from(CHARACTERS) - .where(CHARACTERS.ID.eq(characterId).and(CharacterRepository.legacyCharacterRow()))); - } - 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/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 9ef93f2567..15974fc719 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,11 @@ 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.Condition; import org.jooq.DSLContext; -import org.jooq.Field; import org.jooq.Record; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @@ -34,7 +31,7 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO .eq(tenantId) .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId)) - .and(legacyCharacter(ACTOR_RESOURCE_STATES.CHARACTER_ID))) + .and(CharacterRepository.legacyCharacterExists(ACTOR_RESOURCE_STATES.CHARACTER_ID))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } @@ -68,7 +65,9 @@ public ActorResourceState save(ActorResourceState entity) { DSL.val(entity.getSourceId()), DSL.val(toOffsetDateTime(entity.getCreatedAt())), DSL.val(toOffsetDateTime(entity.getUpdatedAt()))) - .where(legacyCharacter(DSL.val(entity.getCharacterId())))) + .where( + CharacterRepository.legacyCharacterExists( + DSL.val(entity.getCharacterId())))) .returningResult(ACTOR_RESOURCE_STATES.ID) .fetchOne(ACTOR_RESOURCE_STATES.ID); if (id == null) { @@ -90,7 +89,9 @@ public ActorResourceState save(ActorResourceState entity) { ACTOR_RESOURCE_STATES .ID .eq(entity.getId()) - .and(legacyCharacter(ACTOR_RESOURCE_STATES.CHARACTER_ID))) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_RESOURCE_STATES.CHARACTER_ID))) .execute(); if (updated != 1) { throw new IllegalStateException("Legacy resource row is unavailable"); @@ -99,13 +100,6 @@ public ActorResourceState save(ActorResourceState entity) { return entity; } - private static Condition legacyCharacter(Field characterId) { - return DSL.exists( - DSL.selectOne() - .from(CHARACTERS) - .where(CHARACTERS.ID.eq(characterId).and(CharacterRepository.legacyCharacterRow()))); - } - 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/CharacterFriendRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java index 61afc5ee8d..026e102847 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,7 +1,6 @@ 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; @@ -10,7 +9,6 @@ import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; import org.jooq.Condition; import org.jooq.DSLContext; -import org.jooq.Field; import org.jooq.Record; import org.jooq.impl.DSL; import org.springframework.data.domain.Page; @@ -75,8 +73,11 @@ public CharacterFriend save(CharacterFriend entity) { DSL.val(entity.getTenantId()), DSL.val(toLocalDateTime(entity.getCreatedAt()))) .where( - legacyCharacter(DSL.val(entity.getId().getCharacterId())) - .and(legacyCharacter(DSL.val(entity.getId().getFriendId()))))) + CharacterRepository.legacyCharacterExists( + DSL.val(entity.getId().getCharacterId())) + .and( + CharacterRepository.legacyCharacterExists( + DSL.val(entity.getId().getFriendId()))))) .execute(); if (inserted != 1) { throw new IllegalStateException("Legacy friend endpoints are unavailable"); @@ -97,15 +98,8 @@ public void deleteById(CharacterFriendKey key) { } private static Condition legacyFriendEndpoints() { - return legacyCharacter(CHARACTER_FRIEND.CHARACTER_ID) - .and(legacyCharacter(CHARACTER_FRIEND.FRIEND_ID)); - } - - private static Condition legacyCharacter(Field characterId) { - return DSL.exists( - DSL.selectOne() - .from(CHARACTERS) - .where(CHARACTERS.ID.eq(characterId).and(CharacterRepository.legacyCharacterRow()))); + return CharacterRepository.legacyCharacterExists(CHARACTER_FRIEND.CHARACTER_ID) + .and(CharacterRepository.legacyCharacterExists(CHARACTER_FRIEND.FRIEND_ID)); } private CharacterFriend toEntity(Record record) { 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 bcb6ccf6ef..8bddbdf70c 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 @@ -149,6 +149,13 @@ public CharacterRepository(DSLContext dsl) { this.dsl = dsl; } + static Condition legacyCharacterExists(Field characterId) { + return DSL.exists( + DSL.selectOne() + .from(CHARACTERS) + .where(CHARACTERS.ID.eq(characterId).and(legacyCharacterRow()))); + } + static Condition legacyCharacterRow() { return CHARACTERS .ACTOR_IDENTITY_STATUS From f73fd96e4dedb02be2f0be39948265809b2fc22d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:20:09 +1300 Subject: [PATCH 23/28] fix: validate retained lifecycle and canonical activation request identity --- .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 4 +- ...ettlement_retained_lifecycle_integrity.sql | 119 ++++++++ ...tionProtectionPostgresIntegrationTest.java | 263 +++++++++++++++++- ...ayRosterSelectedAssignmentServiceTest.java | 2 +- 5 files changed, 383 insertions(+), 7 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 2b64a1a099..ff0d843442 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -342,4 +342,6 @@ Forward [V1004 lifecycle integrity](../../../../services/account-service/src/mai Forward [V1004.1](../../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql) also rejects a COMMITTED ACTIVE lifecycle whose `lifecycleEpoch` or `rowVersion` is lower than the retained PREPARING counter. Equal or increased counters remain valid; malformed values and other lifecycle binding checks keep V1004's behavior. This remains Account storage integrity validation and does not authenticate World or activate the source path. +Forward [V1004.2](../../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) runs V1004's existing closed PREPARING validator on retained protection evidence before V1004.1's counter comparisons. Thus missing or malformed retained counters cannot bypass monotonicity through SQL `NULL` comparison behavior. It also requires the activation request UUID text at acquisition to equal PostgreSQL's canonical UUID text, rejecting alternate spellings before protection and source-child rows commit. These are storage-integrity checks; they do not backfill retained rows, authenticate World, or activate the source path. + V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. 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 e7eb574002..df5401f986 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,7 +24,9 @@ Exact-source cloud proof for the preceding published `02401d4df0276b04c7f0ff7804 The preceding review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. -Forward V1004.1 rejects a COMMITTED settlement with a regressing World `lifecycleEpoch` or `rowVersion`. The corrected focused run passed all 22 physical PostgreSQL cases with zero failures, errors or skips in 1m40s, including the pinned V1003-to-V1004 historical upgrade, a separate V1004-to-V1004.1 comparison of prior migration ranks/checksums and retained pending-protection/source bytes and `xmin`, both counter decreases retaining writer exclusion, and a valid increased epoch with equal row version. The initial consolidated run failed one new fixture assertion because its proposed row-version decrease was equal to the retained zero; that failed result remains retained. The fixture now starts that case at row version one without changing the guard or other fixture defaults. Account integration static and formatting checks pass; jOOQ generation and the broader Account static/unit checks passed in the initial invocation (1,295 unit cases, four existing filesystem skips). Entity checks also passed with 237 unit and 28 integration cases. These are controlled storage fixtures, not authenticated World production or activation; published-head CI remains separate. +Forward [V1004.1](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql) rejects a COMMITTED settlement with a regressing World `lifecycleEpoch` or `rowVersion`. The corrected focused run passed all 22 physical PostgreSQL cases with zero failures, errors or skips in 1m40s, including the pinned V1003-to-V1004 historical upgrade, a separate V1004-to-V1004.1 comparison of prior migration ranks/checksums and retained pending-protection/source bytes and `xmin`, both counter decreases retaining writer exclusion, and a valid increased epoch with equal row version. The initial consolidated run failed one new fixture assertion because its proposed row-version decrease was equal to the retained zero; that failed result remains retained. The fixture now starts that case at row version one without changing the guard or other fixture defaults. Account integration static and formatting checks pass; jOOQ generation and the broader Account static/unit checks passed in the initial invocation (1,295 unit cases, four existing filesystem skips). Entity checks also passed with 237 unit and 28 integration cases. These are controlled storage fixtures, not authenticated World production or activation; published-head CI remains separate. + +Forward [V1004.2](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) applies the existing closed PREPARING validator during COMMITTED settlement, covering protection rows legitimately retained by V1003 before V1004 acquisition validation. The focused consolidated run passed 24 physical PostgreSQL cases (18 admission and six activation) with zero failures, errors or skips in 1m58s. Controlled V1003 fixtures remove each counter or encode `lifecycleEpoch` with the wrong JSON type, then upgrade through V1004 and V1004.1 to V1004.2 and require SQLSTATE `23514` while preserving protection/source rows, bytes, `xmin`, history and source-writer exclusion. A separate V1004.1-to-V1004.2 fixture requires uppercase activation-request UUID spelling to fail acquisition with SQLSTATE `23514`, leave no protection or source-child rows, and leave the source writer unblocked. jOOQ generation, affected formatting and static checks passed, as did seven focused Entity selection unit cases after correcting their coverage name. These are storage-integrity proofs only; no authenticated World production or activation is claimed. The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. diff --git a/services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql b/services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql new file mode 100644 index 0000000000..c489fa81e5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql @@ -0,0 +1,119 @@ +-- Apply V1004's existing closed PREPARING lifecycle validator to retained protections before +-- comparing their counters, preserving V1004.1's ACTIVE and monotonic settlement checks. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + lifecycle := account_ss_activation_validate_lifecycle(lifecycle_bytes, 'ACTIVE'); + preparing := account_ss_activation_validate_lifecycle( + original.world_preparing_evidence, 'PREPARING'); + IF (lifecycle->>'lifecycleEpoch')::NUMERIC < (preparing->>'lifecycleEpoch')::NUMERIC + OR (lifecycle->>'rowVersion')::NUMERIC < (preparing->>'rowVersion')::NUMERIC THEN + RAISE EXCEPTION 'Committed activation lifecycle counters cannot regress' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Committed activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; +-- [jooq ignore end] + +-- Keep activation-request UUID spelling canonical at the existing Account protection boundary. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR (request_value->>'worldActivationRequestId') IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index dda22d05b2..f48525d474 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -13,6 +13,8 @@ import java.util.Base64; import java.util.HexFormat; import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; @@ -38,11 +40,11 @@ import tools.jackson.databind.json.JsonMapper; /** - * Runs V1003/V1004/V1004.1 against the actual Account PostgreSQL schema and assembled source-writer - * guard. The integrity and currentness fixtures seed related owner rows with upstream producer - * triggers disabled. Protection acquisition, child completeness, settlement and source-writer - * guards remain enabled; they prove SQL currentness/exclusion/immutability only, not authenticated - * activation-protection production. + * Runs V1003/V1004/V1004.1/V1004.2 against the actual Account PostgreSQL schema and assembled + * source-writer guard. The integrity and currentness fixtures seed related owner rows with upstream + * producer triggers disabled. Protection acquisition, child completeness, settlement and + * source-writer guards remain enabled; they prove SQL currentness/exclusion/immutability only, not + * authenticated activation-protection production. */ @Testcontainers(disabledWithoutDocker = true) class AccountStartSessionActivationProtectionPostgresIntegrationTest { @@ -195,6 +197,30 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .get(0, String.class)) .isNotNull(); + String preRetainedLifecycleUpgradeHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.2' ORDER BY installed_rank"; + var preRetainedLifecycleUpgradeHistory = + fixture.dsl().fetch(preRetainedLifecycleUpgradeHistoryQuery).getValues(0, String.class); + Flyway retainedLifecycleUpgrade = activationFlyway(fixture.dataSource(), "1004.2"); + assertThat(retainedLifecycleUpgrade.migrate().migrationsExecuted).isEqualTo(1); + retainedLifecycleUpgrade.validate(); + assertThat( + fixture.dsl().fetch(preRetainedLifecycleUpgradeHistoryQuery).getValues(0, String.class)) + .isEqualTo(preRetainedLifecycleUpgradeHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + fixture .dsl() .fetch( @@ -538,6 +564,233 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .contains("account_start_session_activation_protection_settlements"); } + @Test + void retainedMalformedPreparingLifecycleCannotSettleAfterV1004_2Upgrade() throws Exception { + for (String malformedCounter : + List.of("missing lifecycleEpoch", "missing rowVersion", "numeric lifecycleEpoch")) { + Fixture fixture = fixture("1003"); + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(valid.requestBytes()); + byte[] validPreparingBytes = + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")); + Map malformedPreparing = readJson(validPreparingBytes); + if (malformedCounter.startsWith("missing ")) { + malformedPreparing.remove(malformedCounter.substring("missing ".length())); + } else { + malformedPreparing.put("lifecycleEpoch", 3); + } + byte[] malformedPreparingBytes = jsonBytes(malformedPreparing); + assertThatThrownBy( + () -> WorldCanonicalInstanceLifecycleEvidence.fromStored(malformedPreparingBytes)) + .as("retained PREPARING evidence with %s is not a closed lifecycle", malformedCounter) + .isInstanceOf(IllegalArgumentException.class); + request.put( + "preparingEvidenceBytesBase64", + Base64.getEncoder().encodeToString(malformedPreparingBytes)); + CurrentnessCase malformed = + new CurrentnessCase( + jsonBytes(request), + valid.operationIdentityBytes(), + valid.operationIdentityDigest(), + valid.ownerAttemptId(), + valid.expiryText()); + + // V1003 admitted this exact structurally bound PREPARING carrier. The later migrations + // preserve it and harden settlement; this does not represent authenticated World creation. + acquireProtection(fixture, malformed); + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at, " + + "world_preparing_evidence FROM account_start_session_activation_protections"); + UUID protectionId = stored.get("activation_protection_id", UUID.class); + long protectionFence = stored.get("activation_protection_fence", Long.class); + assertThat(stored.get("world_preparing_evidence", byte[].class)) + .isEqualTo(malformedPreparingBytes); + OffsetDateTime acquiredAt = stored.get("acquired_at", OffsetDateTime.class); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_activation_protection_sources " + + "ORDER BY source_key LIMIT 1") + .get("source_key", String.class); + String protectionRowsQuery = + "SELECT jsonb_build_object('row', to_jsonb(p), 'xmin', p.xmin::TEXT)::TEXT FROM " + + "account_start_session_activation_protections p ORDER BY activation_protection_id"; + String sourceRowsQuery = + "SELECT jsonb_build_object('row', to_jsonb(s), 'xmin', s.xmin::TEXT)::TEXT FROM " + + "account_start_session_activation_protection_sources s " + + "ORDER BY activation_protection_id, source_key"; + var pendingRows = fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class); + var retainedSources = fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class); + assertThat(pendingRows).hasSize(1); + assertThat(retainedSources).hasSize(2); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + Flyway v1004 = activationFlyway(fixture.dataSource(), "1004"); + assertThat(v1004.migrate().migrationsExecuted).isEqualTo(1); + v1004.validate(); + Flyway v1004_1 = activationFlyway(fixture.dataSource(), "1004.1"); + assertThat(v1004_1.migrate().migrationsExecuted).isEqualTo(1); + v1004_1.validate(); + String previousHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.2' ORDER BY installed_rank"; + var previousHistory = fixture.dsl().fetch(previousHistoryQuery).getValues(0, String.class); + Flyway v1004_2 = activationFlyway(fixture.dataSource(), "1004.2"); + assertThat(v1004_2.migrate().migrationsExecuted).isEqualTo(1); + v1004_2.validate(); + assertThat(fixture.dsl().fetch(previousHistoryQuery).getValues(0, String.class)) + .isEqualTo(previousHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT world_preparing_evidence FROM account_start_session_activation_protections") + .get(0, byte[].class)) + .isEqualTo(malformedPreparingBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + UUID activationRequestId = UUID.fromString((String) request.get("worldActivationRequestId")); + byte[][] sourceEvidenceBytes = + fixture + .dsl() + .fetch( + "SELECT source_evidence FROM account_start_session_activation_protection_sources " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)") + .stream() + .map(row -> row.get("source_evidence", byte[].class)) + .toArray(byte[][]::new); + byte[] evidence = + accountEvidence( + protectionId, + protectionFence, + acquiredAt, + malformed.requestBytes(), + bytes("{}"), + sourceEvidenceBytes); + byte[] result = activationResult(activationRequestId, malformedPreparingBytes, "COMMITTED"); + assertSettlementInsertRejected( + fixture, + protectionId, + protectionFence, + activationRequestId, + evidence, + result, + "COMMITTED", + "V1004.2 must reject retained PREPARING evidence with " + malformedCounter); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + } + + @Test + void noncanonicalActivationRequestUuidCannotAcquireProtectionOrBlockSourceWriters() + throws Exception { + Fixture fixture = fixture("1004.1"); + Flyway upgrade = activationFlyway(fixture.dataSource(), "1004.2"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); + + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(valid.requestBytes()); + String uppercaseActivationId = + UUID.fromString("abcdefab-cdef-4abc-8def-abcdefabcdef").toString().toUpperCase(Locale.ROOT); + request.put("worldActivationRequestId", uppercaseActivationId); + CurrentnessCase noncanonical = + new CurrentnessCase( + jsonBytes(request), + valid.operationIdentityBytes(), + valid.operationIdentityDigest(), + valid.ownerAttemptId(), + valid.expiryText()); + + assertThatThrownBy(() -> acquireProtection(fixture, noncanonical)) + .as("activation request UUID spelling must match canonical PostgreSQL UUID text") + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "Activation protection does not retain its exact canonical request fields") + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + assertThat(fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_sources"))) + .isZero(); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_world_participation_sources " + + "ORDER BY source_key LIMIT 1") + .get("source_key", String.class); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + } + @Test void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() throws Exception { Fixture fixture = fixture(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java index f07dc37ab7..9c5ae04f73 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java @@ -267,7 +267,7 @@ void isolatedSelectionRejectsSharedAssignmentReceipt() { } @Test - void changedSnapshotOrActorAbsentFromItFailsBeforeReceiptRead() { + void actorAbsentFromExpectedSnapshotFailsBeforeReceiptRead() { CanonicalGameplayRosterOwnerEvidencePort ownerPort = mock(CanonicalGameplayRosterOwnerEvidencePort.class); CharacterRepository repository = mock(CharacterRepository.class); From fc09b48e830cc6104f3675a911e72272da9af1c8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:50:05 +1300 Subject: [PATCH 24/28] Correct activation tracker anchors and isolate workflow fetch fixtures --- .../player-access-and-session.md | 2 +- dev-tools/tests/pr-retarget-workflow-contract.sh | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 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 df5401f986..cd50b327bd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -164,7 +164,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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. `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. | +| `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. This remains controlled Account integrity proof; authenticated World production and runtime activation remain unproved. | | `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`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 3fd5af5d10..2b0b759038 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -473,12 +473,26 @@ with tempfile.TemporaryDirectory(prefix="firemud-flyway-shallow-") as temporary: if missing.returncode == 0 or "immutable receiving parent commit is unavailable" not in missing.stderr: raise SystemExit(f"shallow checkout did not demonstrate missing parent: {missing.stdout} {missing.stderr}") for event_name in ("pull_request", "push", "workflow_dispatch"): + checkout = Path(temporary) / f"checkout-{event_name}" + subprocess.run(["git", "clone", "--depth=1", fixture.as_uri(), str(checkout)], + check=True, capture_output=True, text=True) + if git_at(checkout, "rev-parse", "HEAD") != child: + raise SystemExit(f"shallow fixture selected the wrong immutable child for {event_name}") + unavailable = subprocess.run(["git", "cat-file", "-e", f"{parent}^{{commit}}"], + cwd=checkout, capture_output=True, text=True) + if unavailable.returncode == 0: + raise SystemExit(f"immutable parent was already available before the {event_name} fetch") + event_command = [sys.executable, str(checker), "--root", str(checkout), "--base-ref", parent] environment.update(FLYWAY_BASE_SHA=parent, FLYWAY_EVENT_NAME=event_name) fetched = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, env=environment, capture_output=True, text=True) if fetched.returncode or git_at(checkout, "rev-parse", parent + "^{commit}") != parent: raise SystemExit(f"exact parent fetch failed for {event_name}: {fetched.stderr}") - available = subprocess.run(command, env=environment, capture_output=True, text=True) + available = subprocess.run(event_command, env=environment, capture_output=True, text=True) + if available.returncode: + raise SystemExit(f"checker rejected exact fetched parent for {event_name}: {available.stdout} {available.stderr}") + fetched_command = event_command + available = subprocess.run(fetched_command, env=environment, capture_output=True, text=True) if available.returncode: raise SystemExit(f"checker rejected exact fetched parent: {available.stdout} {available.stderr}") environment.update(FLYWAY_BASE_SHA="0" * 40, FLYWAY_EVENT_NAME="push") From 412e5bbd70afdd5a89a8e7506956c1c0962c30eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:03:46 +1300 Subject: [PATCH 25/28] Remove completed bootstrap bug observation under bounded stewardship --- design/project-management/ai-observations.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7fa497707c..bf881eb464 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -236,12 +236,6 @@ Entry format: - Expected pattern: read the class’s declared package before specifying a test filter, and verify task execution rather than equating build success with every requested check passing. Enable the repository’s canonical full-check property when selecting static tasks. - Current status: corrected package selection passed 50 focused unit cases; the subsequent runtime fix passed 58 selected unit cases. A separate canonical `-PfullCheck` run executed the required static checks successfully. No validation requirement was waived. -- `2026-10-13`: Fresh-bootstrap discovery needs every required Compose placeholder - - Context: the existing fresh-bootstrap wrapper failed before claiming a run or building images because its configuration-only service discovery supplied the mTLS certificate placeholder but omitted the required authored-world source receipt mount. - - Observation: Compose interpolation rejected the missing directory. The discovery command now supplies a configuration-only receipt path as well; this path is never used by the actual deployment, whose unchanged run-owned claim and capability create and bind the real receipt directory before Compose starts. - - Expected pattern: keep configuration-only placeholders aligned with required Compose mount and environment inputs, then run the existing validate-only preflight when those inputs change. A successful parse establishes configuration completeness, not deployment or owner authority. - - Current status: the existing smoke contract, shellcheck and actual configuration-only parsing pass. The subsequent fresh rebuilt packaged WebSocket and Telnet player-flow baselines pass with the unchanged real run-owned claim; this does not establish canonical owner provenance. - - `2026-10-13`: Native Linux Docker proof can still invoke a Windows credential helper - Context: the claimed Gameplay fresh-bootstrap run rebuilt all service jars and images successfully, then failed before startup while pulling public Redis images. WSL reported `UtilAcceptVsock` and `accept4` timeout errors followed by a Docker credential lookup failure. - Observation: using the native Linux Docker socket does not select a separate client credential configuration. A run-scoped private client configuration can omit unavailable Windows credential helpers while preserving static registry settings and Compose plugin discovery; the global client configuration need not change. From 58ec3605221bfd10b3ddecf8cc7a1604c6c14a87 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:41:51 +1300 Subject: [PATCH 26/28] Close activation carrier mismatch and preserve nullable Entity inserts --- .../account-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 4 +- dev-tools/validation/check-flyway-versions.py | 1 + ...ivation_acquisition_canonical_carriers.sql | 73 +++++++++++ ...tionProtectionPostgresIntegrationTest.java | 121 +++++++++++++++++- .../ActorActiveConditionRepository.java | 39 ++++-- .../ActorResourceStateRepository.java | 31 +++-- .../RetainedActorIdentityIntegrationTest.java | 49 +++++++ 9 files changed, 295 insertions(+), 31 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index ff0d843442..46f6d535cc 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -344,4 +344,6 @@ Forward [V1004.1](../../../../services/account-service/src/main/resources/db/mig Forward [V1004.2](../../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) runs V1004's existing closed PREPARING validator on retained protection evidence before V1004.1's counter comparisons. Thus missing or malformed retained counters cannot bypass monotonicity through SQL `NULL` comparison behavior. It also requires the activation request UUID text at acquisition to equal PostgreSQL's canonical UUID text, rejecting alternate spellings before protection and source-child rows commit. These are storage-integrity checks; they do not backfill retained rows, authenticate World, or activate the source path. +Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path; The 25-case Account physical PostgreSQL gate passes, including 16 whitespace rejection variants and unchanged retained rows/history through upgrade; this remains controlled integrity proof. + V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index bf881eb464..ec9adb9cd0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -259,3 +259,9 @@ Entry format: - Recovery: coordinated controller promotion and actual-endpoint verification restored numeric limits; the owning controller job retains the rollout details. - 2026-10-15: Administrative review settings share a dispatch boundary with provider-backed commands. When removing latency from one setting command, inspect the neighbouring stop/allocation/reset dispatch family and prove each actual entrypoint with Git, GitHub and subprocess access forbidden; method-only fixtures can preserve legacy behavior while missing expensive controller construction. Retain evidence-bound consumption as a separate operation rather than weakening request admission. + +- `2026-10-14`: Native fix attribution needs the exact requested postimage + - Context: Gameplay recorded a requested AA-1.3 tracker-row repair as fixed after its nearby narrative and migration proof passed, while the named row still lacked the migration anchors. + - Observation: the next CLI review exposed the unchanged row. Documentation hygiene checks had passed because they do not verify that a requested semantic target changed. The original native fix record therefore overstated its proof. + - Expected pattern: inspect the exact requested row or declaration before recording an accepted-fix resolution; verify its named anchors instead of relying on a nearby paragraph or a broad substring replacement. + - Current status: the exact row is corrected and verified. An immutable audited resolution correction points to the published repair while retaining the original wrong attribution; the User and Overseer were informed. 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 cd50b327bd..a6c0c1f9c1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,6 +28,8 @@ Forward [V1004.1](../../../services/account-service/src/main/resources/db/migrat Forward [V1004.2](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) applies the existing closed PREPARING validator during COMMITTED settlement, covering protection rows legitimately retained by V1003 before V1004 acquisition validation. The focused consolidated run passed 24 physical PostgreSQL cases (18 admission and six activation) with zero failures, errors or skips in 1m58s. Controlled V1003 fixtures remove each counter or encode `lifecycleEpoch` with the wrong JSON type, then upgrade through V1004 and V1004.1 to V1004.2 and require SQLSTATE `23514` while preserving protection/source rows, bytes, `xmin`, history and source-writer exclusion. A separate V1004.1-to-V1004.2 fixture requires uppercase activation-request UUID spelling to fail acquisition with SQLSTATE `23514`, leave no protection or source-child rows, and leave the source writer unblocked. jOOQ generation, affected formatting and static checks passed, as did seven focused Entity selection unit cases after correcting their coverage name. These are storage-integrity proofs only; no authenticated World production or activation is claimed. +Forward [V1004.3](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) closes the remaining acquisition gap for whitespace-bearing Base64 spellings in the tuple, projection, launch-read, and PREPARING lifecycle carriers. Its controlled PostgreSQL regression matrix covers newline, space, tab, and carriage return per field, requiring SQLSTATE `23514`, no retained protection or source children, and an unblocked source writer; the V1004.2-to-V1004.3 retained-row/history upgrade and all 16 rejection variants pass in the consolidated 3m55s gate. The gate runs 25 fresh Account PostgreSQL cases and full Entity proof of 237 unit and 29 PostgreSQL cases, all without failures, errors or skips. It also proves nullable condition expiry and resource values through the typed legacy INSERT-SELECT path, and passes Account jOOQ, affected static analysis, formatting and documentation checks. Manual-event Flyway self-tests and Ruff pass separately. This remains passive Account storage integrity; no authenticated World production, runtime activation, or full authenticated flow is established. + The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. ### Entity character-creation denial @@ -164,7 +166,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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. `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. This remains controlled Account integrity proof; authenticated World production and runtime activation remain unproved. | +| `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); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.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); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.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); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.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); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.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. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate 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. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `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`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 7154ac45d9..91f3f20330 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -332,6 +332,7 @@ def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str for explicit in (False, True): environment = dict(os.environ) environment.pop("GITHUB_EVENT_PATH", None) + environment.pop("GITHUB_EVENT_NAME", None) environment["FIREMUD_FLYWAY_BASE_REF"] = "0" * 40 command = [sys.executable, str(Path(__file__).resolve()), "--root", tmp] if explicit: diff --git a/services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql b/services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql new file mode 100644 index 0000000000..793342c4b9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql @@ -0,0 +1,73 @@ +-- Require the existing protection fields to retain their canonical Base64 spellings at acquisition. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF regexp_replace(encode(tuple_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'originalPostAuthorizationTupleBytesBase64' + OR regexp_replace(encode(projection_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'accountRedemptionProjectionBytesBase64' + OR regexp_replace(encode(launch_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'gameSessionLaunchReadEvidenceBytesBase64' + OR regexp_replace(encode(preparing_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'preparingEvidenceBytesBase64' THEN + RAISE EXCEPTION 'Activation protection Base64 fields must use canonical encodings' + USING ERRCODE = '23514'; + END IF; + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR (request_value->>'worldActivationRequestId') IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index f48525d474..c8996a6624 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -40,11 +40,11 @@ import tools.jackson.databind.json.JsonMapper; /** - * Runs V1003/V1004/V1004.1/V1004.2 against the actual Account PostgreSQL schema and assembled - * source-writer guard. The integrity and currentness fixtures seed related owner rows with upstream - * producer triggers disabled. Protection acquisition, child completeness, settlement and - * source-writer guards remain enabled; they prove SQL currentness/exclusion/immutability only, not - * authenticated activation-protection production. + * Runs V1003/V1004/V1004.1/V1004.2/V1004.3 against the actual Account PostgreSQL schema and + * assembled source-writer guard. The integrity and currentness fixtures seed related owner rows + * with upstream producer triggers disabled. Protection acquisition, child completeness, settlement + * and source-writer guards remain enabled; they prove SQL currentness/exclusion/immutability only, + * not authenticated activation-protection production. */ @Testcontainers(disabledWithoutDocker = true) class AccountStartSessionActivationProtectionPostgresIntegrationTest { @@ -221,6 +221,36 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .get(0, String.class)) .isNotNull(); + String preCanonicalCarrierUpgradeHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.3' ORDER BY installed_rank"; + var preCanonicalCarrierUpgradeHistory = + fixture.dsl().fetch(preCanonicalCarrierUpgradeHistoryQuery).getValues(0, String.class); + Flyway canonicalCarrierUpgrade = activationFlyway(fixture.dataSource(), "1004.3"); + assertThat(canonicalCarrierUpgrade.migrate().migrationsExecuted).isEqualTo(1); + canonicalCarrierUpgrade.validate(); + assertThat( + fixture.dsl().fetch(preCanonicalCarrierUpgradeHistoryQuery).getValues(0, String.class)) + .isEqualTo(preCanonicalCarrierUpgradeHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT to_regprocedure('account_ss_activation_insert_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT max(version::numeric) FROM flyway_schema_history WHERE version ~ '^[0-9]+(\\.[0-9]+)?$'") + .get(0, java.math.BigDecimal.class)) + .isEqualByComparingTo("1004.3"); + fixture .dsl() .fetch( @@ -791,6 +821,87 @@ void noncanonicalActivationRequestUuidCannotAcquireProtectionOrBlockSourceWriter sourceKey)); } + @Test + void noncanonicalActivationBase64CarriersCannotAcquireProtectionOrBlockSourceWriters() + throws Exception { + Map whitespaceVariants = new LinkedHashMap<>(); + whitespaceVariants.put("newline", '\n'); + whitespaceVariants.put("space", ' '); + whitespaceVariants.put("tab", '\t'); + whitespaceVariants.put("carriage return", '\r'); + Map carrierFields = new LinkedHashMap<>(); + carrierFields.put("tuple", "originalPostAuthorizationTupleBytesBase64"); + carrierFields.put("projection", "accountRedemptionProjectionBytesBase64"); + carrierFields.put("launch read", "gameSessionLaunchReadEvidenceBytesBase64"); + carrierFields.put("PREPARING lifecycle", "preparingEvidenceBytesBase64"); + + for (Map.Entry carrier : carrierFields.entrySet()) { + for (Map.Entry whitespace : whitespaceVariants.entrySet()) { + Fixture fixture = fixture("1004.2"); + Flyway upgrade = activationFlyway(fixture.dataSource(), "1004.3"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); + + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(valid.requestBytes()); + String canonicalBase64 = (String) request.get(carrier.getValue()); + request.put( + carrier.getValue(), + canonicalBase64.substring(0, 4) + whitespace.getValue() + canonicalBase64.substring(4)); + CurrentnessCase noncanonical = + new CurrentnessCase( + jsonBytes(request), + valid.operationIdentityBytes(), + valid.operationIdentityDigest(), + valid.ownerAttemptId(), + valid.expiryText()); + + assertThatThrownBy(() -> acquireProtection(fixture, noncanonical)) + .as( + "%s Base64 carrier with %s must be rejected before protection acquisition", + carrier.getKey(), whitespace.getKey()) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "Activation protection Base64 fields must use canonical encodings") + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + assertThat( + fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_sources"))) + .isZero(); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_world_participation_sources " + + "ORDER BY source_key LIMIT 1") + .get("source_key", String.class); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + } + } + } + @Test void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() throws Exception { Fixture fixture = fixture(); 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 cfdb6aad1a..c9089faae2 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 @@ -91,21 +91,34 @@ public ActorActiveCondition save(ActorActiveCondition entity) { ACTOR_ACTIVE_CONDITIONS.UPDATED_AT) .select( dsl.select( - DSL.val(entity.getTenantId()), - DSL.val(entity.getPlayableStateKey()), - DSL.val(entity.getCharacterId()), - DSL.val(entity.getConditionKey()), - DSL.val(entity.getStackCount()), - DSL.val(entity.getSourceType()), - DSL.val(entity.getSourceId()), - DSL.val(toOffsetDateTime(entity.getStartedAt())), - DSL.val(toOffsetDateTime(entity.getExpiresAt())), - DSL.val(entity.getEffectPayloadJson()), - DSL.val(toOffsetDateTime(entity.getCreatedAt())), - DSL.val(toOffsetDateTime(entity.getUpdatedAt()))) + DSL.val(entity.getTenantId(), ACTOR_ACTIVE_CONDITIONS.TENANT_ID), + DSL.val( + entity.getPlayableStateKey(), + ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY), + DSL.val(entity.getCharacterId(), ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID), + DSL.val(entity.getConditionKey(), ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY), + DSL.val(entity.getStackCount(), ACTOR_ACTIVE_CONDITIONS.STACK_COUNT), + DSL.val(entity.getSourceType(), ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE), + DSL.val(entity.getSourceId(), ACTOR_ACTIVE_CONDITIONS.SOURCE_ID), + DSL.val( + toOffsetDateTime(entity.getStartedAt()), + ACTOR_ACTIVE_CONDITIONS.STARTED_AT), + DSL.val( + toOffsetDateTime(entity.getExpiresAt()), + ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT), + DSL.val( + entity.getEffectPayloadJson(), + ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON), + DSL.val( + toOffsetDateTime(entity.getCreatedAt()), + ACTOR_ACTIVE_CONDITIONS.CREATED_AT), + DSL.val( + toOffsetDateTime(entity.getUpdatedAt()), + ACTOR_ACTIVE_CONDITIONS.UPDATED_AT)) .where( CharacterRepository.legacyCharacterExists( - DSL.val(entity.getCharacterId())))) + DSL.val( + entity.getCharacterId(), ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID)))) .returningResult(ACTOR_ACTIVE_CONDITIONS.ID) .fetchOne(ACTOR_ACTIVE_CONDITIONS.ID); if (id == null) { 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 15974fc719..83ee788a5b 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 @@ -54,20 +54,27 @@ public ActorResourceState save(ActorResourceState entity) { ACTOR_RESOURCE_STATES.UPDATED_AT) .select( dsl.select( - DSL.val(entity.getTenantId()), - DSL.val(entity.getPlayableStateKey()), - DSL.val(entity.getCharacterId()), - DSL.val(entity.getStatKey()), - DSL.val(entity.getCurrentValue()), - DSL.val(entity.getMaxValue()), - DSL.val(entity.getBaseValue()), - DSL.val(entity.getSourceType()), - DSL.val(entity.getSourceId()), - DSL.val(toOffsetDateTime(entity.getCreatedAt())), - DSL.val(toOffsetDateTime(entity.getUpdatedAt()))) + DSL.val(entity.getTenantId(), ACTOR_RESOURCE_STATES.TENANT_ID), + DSL.val( + entity.getPlayableStateKey(), + ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY), + DSL.val(entity.getCharacterId(), ACTOR_RESOURCE_STATES.CHARACTER_ID), + DSL.val(entity.getStatKey(), ACTOR_RESOURCE_STATES.STAT_KEY), + DSL.val(entity.getCurrentValue(), ACTOR_RESOURCE_STATES.CURRENT_VALUE), + DSL.val(entity.getMaxValue(), ACTOR_RESOURCE_STATES.MAX_VALUE), + DSL.val(entity.getBaseValue(), ACTOR_RESOURCE_STATES.BASE_VALUE), + DSL.val(entity.getSourceType(), ACTOR_RESOURCE_STATES.SOURCE_TYPE), + DSL.val(entity.getSourceId(), ACTOR_RESOURCE_STATES.SOURCE_ID), + DSL.val( + toOffsetDateTime(entity.getCreatedAt()), + ACTOR_RESOURCE_STATES.CREATED_AT), + DSL.val( + toOffsetDateTime(entity.getUpdatedAt()), + ACTOR_RESOURCE_STATES.UPDATED_AT)) .where( CharacterRepository.legacyCharacterExists( - DSL.val(entity.getCharacterId())))) + DSL.val( + entity.getCharacterId(), ACTOR_RESOURCE_STATES.CHARACTER_ID)))) .returningResult(ACTOR_RESOURCE_STATES.ID) .fetchOne(ACTOR_RESOURCE_STATES.ID); if (id == null) { 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 45a9ba416b..11ab811397 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 @@ -13,8 +13,12 @@ import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; 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.v1.PlayableStateScope; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -74,6 +78,8 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private CharacterRepository characterRepository; @Autowired private ActorIdentityRepository actorIdentityRepository; + @Autowired private ActorActiveConditionRepository conditionRepository; + @Autowired private ActorResourceStateRepository resourceRepository; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private Flyway flyway; @@ -140,6 +146,49 @@ void legacySaveAllocatesQuarantinedUuidAndPreservesLegacyReadbackAndUpdates() { .isEqualTo(characterUuid); } + @Test + void legacyConditionalInsertsPreserveNullablePostgresColumnTypes() { + Character actor = new Character(); + actor.setTenantId(tenantId); + actor.setAccountId(accountId); + actor.setPlayableStateKey("instance:" + instanceId); + actor.setName("Nullable legacy values"); + actor = characterRepository.save(actor); + + ActorActiveCondition condition = new ActorActiveCondition(); + condition.setTenantId(tenantId); + condition.setPlayableStateKey(actor.getPlayableStateKey()); + condition.setCharacterId(actor.getId()); + condition.setConditionKey("permanent-condition"); + condition.setSourceType("TEST"); + conditionRepository.save(condition); + assertThat(condition.getId()).isNotNull(); + var conditions = + conditionRepository.findActiveForCharacter( + tenantId, actor.getPlayableStateKey(), actor.getId(), java.time.Instant.now()); + assertThat(conditions).hasSize(1); + assertThat(conditions.getFirst().getExpiresAt()).isNull(); + assertThat(conditions.getFirst().getSourceId()).isNull(); + assertThat(conditions.getFirst().getEffectPayloadJson()).isNull(); + + ActorResourceState resource = new ActorResourceState(); + resource.setTenantId(tenantId); + resource.setPlayableStateKey(actor.getPlayableStateKey()); + resource.setCharacterId(actor.getId()); + resource.setStatKey("nullable-stat"); + resource.setCurrentValue(5L); + resourceRepository.save(resource); + assertThat(resource.getId()).isNotNull(); + var resources = + resourceRepository.findByTenantIdAndPlayableStateKeyAndCharacterIdOrderByStatKeyAsc( + tenantId, actor.getPlayableStateKey(), actor.getId()); + assertThat(resources).hasSize(1); + assertThat(resources.getFirst().getCurrentValue()).isEqualTo(5L); + assertThat(resources.getFirst().getMaxValue()).isNull(); + assertThat(resources.getFirst().getBaseValue()).isNull(); + assertThat(resources.getFirst().getSourceId()).isNull(); + } + @Test void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { // SQL fixtures prove storage isolation only; they provide no owner authority or runtime From 05e5aeb73d386b35ca222162d8617230c0f8d59a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:53:10 +1300 Subject: [PATCH 27/28] Keep activation proof results at the implementation tracker --- .../microservices/account-service/runtime-and-data.md | 2 +- 1 file changed, 1 insertion(+), 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 46f6d535cc..a71a75a8c2 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -344,6 +344,6 @@ Forward [V1004.1](../../../../services/account-service/src/main/resources/db/mig Forward [V1004.2](../../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) runs V1004's existing closed PREPARING validator on retained protection evidence before V1004.1's counter comparisons. Thus missing or malformed retained counters cannot bypass monotonicity through SQL `NULL` comparison behavior. It also requires the activation request UUID text at acquisition to equal PostgreSQL's canonical UUID text, rejecting alternate spellings before protection and source-child rows commit. These are storage-integrity checks; they do not backfill retained rows, authenticate World, or activate the source path. -Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path; The 25-case Account physical PostgreSQL gate passes, including 16 whitespace rejection variants and unchanged retained rows/history through upgrade; this remains controlled integrity proof. +Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path. Current proof and limits are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. From 5da24f222334aadde0133b04a4b5dcb20c75354c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:25:27 +1300 Subject: [PATCH 28/28] Type guarded legacy friend inserts and simplify assignment test helper --- .../repository/CharacterFriendRepository.java | 17 +++-- ...eseededActorAssignmentIntegrationTest.java | 60 ++++++----------- .../RetainedActorIdentityIntegrationTest.java | 66 +++++++++++++++++++ 3 files changed, 97 insertions(+), 46 deletions(-) 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 026e102847..ba8f53e915 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 @@ -68,16 +68,21 @@ public CharacterFriend save(CharacterFriend entity) { CHARACTER_FRIEND.CREATED_AT) .select( dsl.select( - DSL.val(entity.getId().getCharacterId()), - DSL.val(entity.getId().getFriendId()), - DSL.val(entity.getTenantId()), - DSL.val(toLocalDateTime(entity.getCreatedAt()))) + DSL.val(entity.getId().getCharacterId(), CHARACTER_FRIEND.CHARACTER_ID), + DSL.val(entity.getId().getFriendId(), CHARACTER_FRIEND.FRIEND_ID), + DSL.val(entity.getTenantId(), CHARACTER_FRIEND.TENANT_ID), + DSL.val( + toLocalDateTime(entity.getCreatedAt()), CHARACTER_FRIEND.CREATED_AT)) .where( CharacterRepository.legacyCharacterExists( - DSL.val(entity.getId().getCharacterId())) + DSL.val( + entity.getId().getCharacterId(), + CHARACTER_FRIEND.CHARACTER_ID)) .and( CharacterRepository.legacyCharacterExists( - DSL.val(entity.getId().getFriendId()))))) + DSL.val( + entity.getId().getFriendId(), + CHARACTER_FRIEND.FRIEND_ID))))) .execute(); if (inserted != 1) { throw new IllegalStateException("Legacy friend endpoints are unavailable"); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 62851cfa7b..5726f1b3a9 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -159,8 +159,7 @@ void postgresMigrationInstallsAndEnforcesDeferredAssignmentForeignKeys() { accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); UUID missingCharacterUuid = UUID.randomUUID(); UUID invalidOperationUuid = UUID.randomUUID(); @@ -492,24 +491,21 @@ void exactRetryReturnsSamePersistedActorAndChangedIntentConflictsBeforeAllocatio accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); PreseededActorAssignmentResult retry = assign( assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); PreseededActorAssignmentResult changedIntent = assign( assignmentUuid, accountUuid, 5L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "b"); + "Assigned Actor"); assertThat(first.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); assertThat(retry).isEqualTo(first); @@ -553,8 +549,7 @@ void committedReceiptIsExactReplayStableAndDeniedForChangedOrQuarantinedActor() accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); var evidence = evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); var expectedTarget = @@ -694,8 +689,7 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Canonical Actor", - "a"); + "Canonical Actor"); Long entityTenantRowId = jdbcTemplate.queryForObject( "SELECT entity_tenant_row_id FROM entity_tenant_identities " @@ -1116,8 +1110,7 @@ void selectedAssignmentReadRequiresExactOwnerTargetAndCurrentActorProvenance() { accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Selected Actor", - "a"); + "Selected Actor"); var ownerEvidence = evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); var expectedTarget = assignmentRequest(ownerEvidence).expectedTarget(); @@ -1227,32 +1220,28 @@ void sameAssignmentUuidConflictsForChangedAccountScopeOrPayloadWithoutReturningA accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); PreseededActorAssignmentResult changedAccount = assign( assignmentUuid, secondAccountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "b"); + "Assigned Actor"); PreseededActorAssignmentResult changedScope = assign( assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, - "Assigned Actor", - "c"); + "Assigned Actor"); PreseededActorAssignmentResult changedPayload = assign( assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Renamed Actor", - "d"); + "Renamed Actor"); assertThat(original.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); assertConflictWithoutActorDisclosure(changedAccount); @@ -1282,16 +1271,14 @@ void separateAuthorizedAssignmentsCanCreateMultipleActorsEvenWithSameDisplayName accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); PreseededActorAssignmentResult second = assign( secondAssignmentUuid, secondAccountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "b"); + "Assigned Actor"); assertThat(first.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); assertThat(second.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); @@ -1336,8 +1323,7 @@ void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() thr accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Concurrent Actor", - "a"); + "Concurrent Actor"); }); Future second = executor.submit( @@ -1351,8 +1337,7 @@ void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() thr accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Concurrent Actor", - "b"); + "Concurrent Actor"); }); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); @@ -1381,8 +1366,7 @@ void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() thr accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Concurrent Actor", - "retry")) + "Concurrent Actor")) .isEqualTo(loser); assertThat( jdbcTemplate.queryForObject( @@ -1426,8 +1410,7 @@ void conflictingNamespaceScopeProofRollsBackGuardAndDoesNotPromoteOrAllocateActo accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a")) + "Assigned Actor")) .isInstanceOf(RuntimeException.class); assertThat( @@ -1451,8 +1434,7 @@ void assignmentReplayAndOwnerMappingsRejectDeleteAndTruncate() { accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a"); + "Assigned Actor"); assertThatThrownBy( () -> @@ -1482,8 +1464,7 @@ void assignmentReplayAndOwnerMappingsRejectDeleteAndTruncate() { accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor", - "a")) + "Assigned Actor")) .isEqualTo(assigned); } @@ -1492,8 +1473,7 @@ private PreseededActorAssignmentResult assign( UUID actorAccountUuid, long catalogRevision, PlayableStateScope scope, - String displayName, - String digestFirstHexDigit) { + String displayName) { PreseededActorAssignmentOwnerEvidence target = evidence(operationUuid, actorAccountUuid, catalogRevision, scope); PreseededActorAssignmentRequest request = assignmentRequest(target, displayName); 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 11ab811397..df51b1a7b4 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 @@ -6,6 +6,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -16,9 +17,12 @@ 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.entity.CharacterFriend; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; 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.CharacterFriendRepository; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -81,6 +85,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private ActorActiveConditionRepository conditionRepository; @Autowired private ActorResourceStateRepository resourceRepository; @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private CharacterFriendRepository friendRepository; @Autowired private Flyway flyway; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @@ -189,6 +194,67 @@ void legacyConditionalInsertsPreserveNullablePostgresColumnTypes() { assertThat(resources.getFirst().getSourceId()).isNull(); } + @Test + void legacyFriendInsertUsesGeneratedColumnTypesAndRejectsOwnerResolvedEndpoints() { + Character character = new Character(); + character.setTenantId(tenantId); + character.setAccountId(accountId); + character.setPlayableStateKey("instance:" + instanceId); + character.setName("Legacy friend source"); + character = characterRepository.save(character); + + Character friendActor = new Character(); + friendActor.setTenantId(tenantId); + friendActor.setAccountId(accountId); + friendActor.setPlayableStateKey("instance:" + instanceId); + friendActor.setName("Legacy friend target"); + friendActor = characterRepository.save(friendActor); + + Instant createdAt = Instant.parse("2026-10-15T12:34:56Z"); + CharacterFriendKey friendKey = new CharacterFriendKey(); + friendKey.setCharacterId(character.getId()); + friendKey.setFriendId(friendActor.getId()); + CharacterFriend friend = new CharacterFriend(); + friend.setId(friendKey); + friend.setTenantId(tenantId); + friend.setCreatedAt(createdAt); + + friendRepository.save(friend); + + CharacterFriend readBack = friendRepository.findById(friendKey).orElseThrow(); + assertThat(readBack.getId().getCharacterId()).isEqualTo(character.getId()); + assertThat(readBack.getId().getFriendId()).isEqualTo(friendActor.getId()); + assertThat(readBack.getTenantId()).isEqualTo(tenantId); + assertThat(readBack.getCreatedAt()).isEqualTo(createdAt); + assertThat(friendRepository.countByTenantId(tenantId)).isEqualTo(1L); + + insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + long ownerResolvedId = + insertActor( + "Owner-resolved friend endpoint", + UUID.randomUUID(), + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + CharacterFriendKey rejectedKey = new CharacterFriendKey(); + rejectedKey.setCharacterId(character.getId()); + rejectedKey.setFriendId(ownerResolvedId); + CharacterFriend rejectedFriend = new CharacterFriend(); + rejectedFriend.setId(rejectedKey); + rejectedFriend.setTenantId(tenantId); + rejectedFriend.setCreatedAt(createdAt); + + assertThatThrownBy(() -> friendRepository.save(rejectedFriend)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Legacy friend endpoints are unavailable"); + } + @Test void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { // SQL fixtures prove storage isolation only; they provide no owner authority or runtime