diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index 23cd54ce1d..dd9dbfa771 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -210,6 +210,8 @@ FIREMUD_SERVICES_GAME_LOGIC_SERVICE=game-logic-service:6565 FIREMUD_SERVICES_LOGGING_ADMIN_SERVICE=logging-admin-service:6565 ``` +Game Session separately consumes the non-secret `GAME_LOGIC_READINESS_URL` as `game.logic.readiness-url`. Its local default is `http://game-logic-service:8080/actuator/health/readiness`; the production profile requires an explicit binding and remains unready when absent. Kustomize supplies it through `firemud-config` in `k8s/base/firemud-db-env.yaml`; hosted Helm supplies it through `previewStack.sharedConfig` in `k8s/helm/firemud/values-hosted-shared.example.yaml`. It is an HTTP URL, not a `ServiceEndpointsProperties` gRPC override. URL constraints and readiness behavior are owned by [Game Session Operations](../microservices/game-session-service/operations.md#readiness-and-liveness), with local binding details in [Game Session Configuration](../microservices/game-session-service/configuration.md). + Player-facing environments (`hobby-self-hosted`, staging, production) must treat these overrides as exceptional. The compliant default is to leave them unset and use in-environment Kubernetes DNS/service discovery. If any `FIREMUD_SERVICES_*` override is required in a player-facing environment, deployment preflight must validate it against `design/operations/environments//expected-bindings.yaml`; undeclared overrides or values that resolve into another environment boundary must fail deployment. --- diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index bd0c08132c..a8edc96cd5 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -69,7 +69,9 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The coherent selected-publication receiver installs immutable source inventories, selected owner attestations and mandatory fresh-v2 operation/capture guards through V1023, then asset-bound reviewed-base v2 guards in V1024. Current Java callers supply complete v2 operation evidence and the ordinary asset owner participates in synchronized source and export projection. Original v1 operation/review bytes remain readable history without fresh write authority. This adds no registered publication ingress or activation authority. The canonical retention and fresh-operation rule is in [Version Control](./version-control.md#selected-publication-storage-and-retained-operations), with physical owner proof, controlled-input limits and current qualification in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). -The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. +The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. Both adapters return retryable `UNAVAILABLE` for connection acquisition and transaction timeouts, and `INTERNAL` for permanent propagation, rollback, nested-transaction and isolation failures, with bounded descriptions that do not expose underlying storage errors. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no generic registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. + +The existing default-off run-owned fixture configuration registers operation-scoped wrappers for those same two RPCs. Before decoding selectors, each wrapper rejects caller context and requires the fixed `dev` World workload URI, its exact mounted leaf, and immutable run/project/capability/receipt/CA configuration. Exact selectors must match the retained closed fixture source and Version. Successful reads independently qualify actual committed creation, source, Version, bundle and descriptor owners plus the already sealed policy header; they never resolve a descriptor, seal a policy, allocate state or repair missing owners. The two exact RPC names bypass bearer validation in both profiles; the generic kernels retain their independent peer checks and remain unregistered. This fixture variant grants no Human source application, activation or admission authority. Its focused proof and runtime limits belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#fixed-fixture-source-and-version-reads). The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index 4100672b7a..a5104b03b2 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -21,6 +21,7 @@ TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC | `GAME_SOLO_TICK_BUDGET_MS` | Execution budget for isolated solo ticks | `500` | | `GAME_TICK_MAX_COMMANDS` | Max commands staged from the queue each tick | `50` | | `FIREMUD_SERVICES_GAME_LOGIC_SERVICE` | gRPC endpoint (`host:port`) for Game Logic Service | *(none)* | +| `GAME_LOGIC_READINESS_URL` | Internal Game Logic actuator readiness URL bound to `game.logic.readiness-url`; required explicitly in `prod` | Local: `http://game-logic-service:8080/actuator/health/readiness`; `prod`: empty, unready | | `FIREMUD_SERVICES_WORLD_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for World Management Service | `world-management-service:6565` | | `FIREMUD_SERVICES_ENTITY_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for Entity Management Service | `entity-management-service:6565` | | `FIREMUD_CONFLICT_TTL_SECONDS` | TTL for conflict hotspot tracking in Redis | `300` | @@ -45,6 +46,8 @@ The generated reference carries the current defaults, descriptions, valid values ## Configuration Notes +`GAME_LOGIC_READINESS_URL` is non-secret deployment configuration, separate from the gRPC `host:port`. Kustomize's `firemud-config` and hosted Helm's shared configuration provide the internal URL. An absent production binding leaves readiness false. Accepted URL shape and the required Ping/HTTP conjunction remain owned by [Operations: Readiness and Liveness](./operations.md#readiness-and-liveness). + - Settings distribution follows [ADR 0113](../../decisions/adr-0113-bounded-pull-settings-distribution-with-freshness-classes.md): Game Session consumes revisioned snapshots through a bounded local cache and must retain revision, age, provenance, and degraded/expired state in its effective-settings diagnostics. The current short TTL plus explicit refresh/evict behavior is a local implementation seam; class-specific freshness outcomes and an authoritative fence for restrictive settings remain gaps. No generalized push channel or concrete TTL is implied. - Environment variables configure PostgreSQL and Redis connections via `DatabaseAutoConfiguration` and `RedisProperties`. - `.env.sample` contains example values for local development. diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 2305ae41cb..0f3a76ddcb 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -28,9 +28,11 @@ Before deploying the new Game Session admission validation, Automation must alre - required Redis-backed session and tick infrastructure is usable; - the readiness-only local round-trip canaries for session-context storage and command-queue storage both succeed; - Account Service authentication is reachable through a bounded readiness-only authentication probe; and - - Game Logic is reachable for the first gameplay command path through a bounded readiness-only `ResolveLook` probe, with Game Logic in turn proving readiness for the downstream services needed to satisfy the first `LOOK`. + - Game Logic answers its existing authenticated gRPC `Ping` with `pong`, without an application error, within a two-second readiness deadline, and its configured internal `/actuator/health/readiness` endpoint returns a successful HTTP status through the shared bounded HTTP checker. Both checks are required; Game Logic retains ownership of its private World Management and Entity Management dependency probes. - A successful `LOGIN` without a safe first `LOOK` is not sufficient readiness for new player traffic. -- Synthetic identifiers used by these canaries are explicitly reserved for readiness-only traffic so they cannot collide with real gameplay state. +- Local store and Account canaries use reserved readiness-only identifiers. The Game Logic checks carry no player execution context, synthetic player identity, or admitted routing bundle. They do not invoke player `ResolveLook` or bypass its admission guards. +- The HTTP destination must use HTTP or HTTPS, contain a host and exactly `/actuator/health/readiness`, and contain no user information, query, or fragment. Missing, malformed, unavailable, or unsuccessful readiness responses fail closed. The shared checker bounds connection establishment to one second and the request to two seconds; Ping uses the existing authenticated gRPC client configuration. +- These checks establish dependency readiness for the exposed service boundary. Successful player admission, executable `LOOK`, and genuine owner handoffs require their separate runtime proof; Ping and dependency readiness cannot supply player authority. Current implementation, focused proof, and remaining runtime gaps are recorded under [PO-4.2](../../../project-management/implementation-tracking/platform-operations-and-delivery.md). - Readiness transition observability uses the shared contract from [Deployment Environments](../../infrastructure/deployment-environments.md): `firemud.readiness.current`, `firemud.readiness.transitions`, and structured logs keyed by the curated dependency names `accountService`, `sessionContextStore`, `commandQueueStore`, and `gameLogicService`. ## Operational Notes diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 8ea3a2d3b9..5d6ae36808 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -64,6 +64,10 @@ Game Design now has immutable `COMMAND` and `REALM_ENTRY_POLICY` source, reviewe The Game Design owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented with immutable request/digest/tenant-source evidence. The canonical behavior is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback). The bounded implementation and its focused proof are named in the [Capability Status](#capability-status) and [Validation and Proof](#validation-and-proof) entries below. These prove bounded storage and readback, not authenticated creator authorization, Account enrollment, runtime admission, or a playable environment. No creation RPC or activation is introduced, and broader capability ratings remain unchanged. +### Fixed-fixture source and version reads + +The default-off run-owned fixture exposes exact authored-world source and Version reads through the existing Game Design RPCs. The normative boundary is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); this entry records only bounded implementation and proof status. At GDS component revision `46074cf976759e3fb19cafc0bea7d16e544db555`, 519 unit cases and 141 native cases passed fresh; generation, static analysis, formatting, and documentation checks passed separately. Receiving evidence at `9984` includes 49 fresh Game Session readiness cases and 15 fresh Game Design source/Version cases; 21 Game Logic cases were reused. Smoke covered fresh and restarted services with the fixture forced false, proving ordinary default-off behavior only. This does not prove packaged enabled-fixture runtime, current Human source, runtime activation, canonical World, first `OPEN`, or a genuine handoff. + ### Run-owned authored-world fixture repair The earlier #3151 full-stack smoke used a numeric-only request and failed at Game Design's closed canonical authored-world source check; that result remains the baseline failure and is not repaired-candidate proof. The current producer captures real committed release-bundle, artifact-state, and version-state projections with the registered source and verifies them before resolving the exact source-bound default-template descriptor. It commits the actual descriptor resolution, independently reads it with its real request/result digests, and rereads source and current owner snapshots before atomically publishing the complete immutable run/project receipt. The capability and receipt bind actual Game Session and World Management leaf certificates to the same CA. This local handoff does not grant production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` authority; those calls authenticate exact candidate peers and then deny before owner reads pending genuine operation authority. The normative fixture boundary is owned by [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), while receipt ownership remains in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). @@ -114,6 +118,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | Fresh-tenant identity prerequisite | `partial` | `proven` for bounded fresh-creation persistence and exact Account/Game Session receipt read only | [Canonical tenant identity and fresh-creation readback](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback) | [GameTenantCreationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java); [TenantIdentityGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java); [V29 canonical game tenant identity](../../../services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql); [V30 game tenant creation operations](../../../services/game-design-service/src/main/resources/db/migration/V30__game_tenant_creation_operations.sql) | [GameTenantCreationRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java); [GameTenantIdentityRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java); [TenantIdentityGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java); [TenantIdentityGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java); [GrpcServerPeerIdentityClientInterceptorTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java); [GameTenantCreationRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java); [FreshTenantCreationEvidenceTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java) | [Account identity and enrollment](./player-access-and-session.md); [realm routing and playable state](./realm-routing-and-playable-state.md) | Partial: bounded owner-local persistence and exact mTLS receipt read exist. Authenticated creator authorization, Account enrollment, runtime admission, and a playable environment remain unavailable. No creation RPC or activation is introduced. | +| Fixed-fixture source and Version reads | `partial` | `proven` for exact source/Version owner reads and bounded failure classification in the default-off fixture path; packaged enabled-fixture runtime remains unproved. | [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status) | [AuthoredWorldSourceReadGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java); [RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java) | [RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java); component and receiver proof recorded in [fixed-fixture source and Version reads](#fixed-fixture-source-and-version-reads) | [World runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [Game Logic](./gameplay-rules-entities-and-effects.md) | Controlled source/owner proof only; packaged smoke qualifies the default-off baseline. No packaged enabled-fixture runtime, current Human source, runtime activation, canonical World, first `OPEN`, or genuine handoff proof. | | `EA-3.2` Creator authoring applications | `partial` | `audited` | [Frontend architecture](../../architecture/system-architecture-frontend.md); [creator journeys](../../product/user-journeys/creators.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md) | [App.tsx](../../../web-client/src/App.tsx); [GameEditor.tsx](../../../web-client/src/GameEditor.tsx); [ScriptEditor.tsx](../../../web-client/src/ScriptEditor.tsx); [GameDesignGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java) | [GameDesignGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java); [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the [web-client README](../../../web-client/README.md) records a starter React surface and backend authoring APIs exist, but the designed creator application, accessible editor workflows, preview, conflict resolution, and focused frontend proof are absent. ADR 0124, ADR 0126, and ADR 0129 define the profile, scoped-proposal, and Draft-fence target behavior; implementation and focused proof remain absent. | | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 96d18ab48c..88761d0aab 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -18,6 +18,10 @@ The migration-preservation correction restores the exact original V1005/V1006 Gi ### Run-owned canonical source handoff +The source-first receiving merge `96ca0b8ac07946969a13be659cf65af101e82c41` on parent `f98e2e6309a2d771286ba7743a1bbb73c10c4c24` preserves all 24 owned paths and their runtime/test postimages. Its 70 readiness unit cases execute freshly with zero failures, errors or skips; the unchanged fifteen Source/Version unit cases retain their preceding successful execution. Affected static and documentation checks pass. Fresh source-built baseline and same-version restart both pass WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK`, followed by successful original-capability teardown. This qualifies dependency readiness with the retained bootstrap; canonical World/first-`OPEN` and genuine owner handoffs remain open. + +The dependency-readiness child also supplies the actual random-port Game Logic HTTP readiness URL to the shared cross-service stack, before caller-specific overrides. Its initial source omitted this test producer, leaving the container-DNS default in a localhost harness; the inherited TCP Proxy CI job failed while waiting for Game Session readiness. The corrected local inputs on parent `7ab19d077f021b044b2d45409d892324c6204a48` freshly pass all 14 `TelnetGatewayGameSessionAccountCrossServiceIntegrationTest` cases with zero failures, errors or skips, including traffic-admission readiness, plus test-fixture Checkstyle, SpotBugs and formatting. The cloud job selected 17 total cases; this focused local result does not relabel the other three as freshly executed. The nested Game Logic restart also preserves its actual HTTP and gRPC ports, so the configured readiness destination remains valid. Ten focused WebSocket cross-service cases freshly pass with zero failures, errors or skips, including unchanged persisted LOOK behavior, HTTP-port identity and both service readiness endpoints after restart; fixture/cross-service static checks and formatting pass. This is controlled legacy-flow fixture proof, not deployed recovery or canonical player authority. Controlled nested services and Account/World/Entity fixtures qualify the stated cross-service behavior, not genuine owner custody, protected activation or complete playable closure. + The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the current source-first candidate. The source-first owner consumes the closed run/project-bound Game Design receipt with actual fresh creation and source evidence, all four immutable launch snapshots (release bundle, artifact state, version state, and persisted launch descriptor), and the fixture policy seal. It pins the exact receipt across reads and binds canonical preparation to the registered source. Game Session obtains its typed fixture carrier only through the trusted data-package parser; `RunOwnedCanonicalLaunchPreparationOwner` exposes `createVerifiedFixtureStartingLaunch` plus independent `readVerifiedFixtureLaunch` only through explicit preparation, with no scheduler. The new `GetRunOwnedFixtureLaunchAssociation` RPC is read-only and reads the canonical repository. The explicit owner is not wired into the retained published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap or existing `GameInstanceServiceImpl` behavior. This path has no descriptor-resolution or preflight phase and invokes none of the three production Game Design release/version/artifact read RPCs. Generic `StartSession` cannot construct or select the fixture carrier. The receipt also carries the exact Game Session and World Management recipient pins; it does not grant production RPC authority. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. Historical focused unit tests cover immutable replay, descriptor comparison, certificate-pin mismatch, malformed/unknown evidence, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches; those results do not qualify the current source-first split. The new `RunOwnedCanonicalLaunchPreparationOwnerTest` and fixture association-read tests passed eight and seven cases respectively in the current focused gate described above. All fourteen [fixture capability cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java) passed in the 2026-10-12 canonical Game Session full check; the whole unit task ran 2,080 cases with seventeen environment-dependent skips and no failures. This remains historical local unit proof. The prior `aaecdcc92e5de67047a7af80649b30ed773c91c1` revision rebuilt and booted the run-owned Compose images and passed WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` in [runtime run 38190595607](https://github.com/benhook1013/FireMUD/actions/runs/38190595607); that result belongs to that revision. Bounded source proof on `4896eaa8939cd4783106c9dbe0ef8e88515dd6ed` covers 2,207 unit and 39 cross-service cases. Current native PostgreSQL proof comprises 278 unique cases across the 277-case previous pass and the final 10-owner pass, with nine overlapping cases. The raw full integration attempt failed; only the qualified focused owner proof is established. The source-first reconstruction’s fresh and restart packaged `PLAY`/`LOOK` proof is qualified above; these historical native counts retain their original attribution. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index ec406ea991..307ad6db02 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -78,7 +78,7 @@ These links record implementation and proof gaps; they do not claim that the cor | `PO-3.3` Object storage, CDN, registry, and platform asset delivery infrastructure | `partial` | `proven` | [Asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [infrastructure](../../architecture/infrastructure/README.md) | [AssetStoreConfig.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreConfig.java); [AssetController.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java); [V10__version_asset_artifact.sql](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [MinIO deployment.yaml](../../../k8s/minio/deployment.yaml); [runtime-images.yml](../../../.github/workflows/runtime-images.yml) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java); [validate-helm.sh](../../../dev-tools/validation/validate-helm.sh); [smoke-image-env-contract.sh](../../../dev-tools/tests/smoke-image-env-contract.sh) | [Authoring](./game-authoring-publishing-and-activation.md); [player experience](./player-experience-commands-and-communication.md) | Production CDN lifecycle, richer registry operations, and creator-facing asset delivery remain. | | `PO-3.4` Backup, restore, disaster recovery, and self-hosted recovery | `partial` | `drift-found`: bounded online-dump and backup-verifier helper/image contract checks, non-executing restore wiring, reset, and restart seams are proven locally; no live backup existence/reachability is proven, and the broader recovery capability remains unproven | [Backup/recovery](../../architecture/system-architecture-backup-recovery.md); [recovery evidence](../../architecture/system-architecture-backup-recovery-evidence-and-compliance.md); [CI/CD](../../architecture/system-architecture-cicd.md) | [schedule.yaml](../../../k8s/velero/schedule.yaml); [verify-backups-cronjob.yaml](../../../k8s/velero/verify-backups-cronjob.yaml); [manual-backup-restore.yml](../../../.github/workflows/manual-backup-restore.yml); [pg-dump-rotate.sh](../../../dev-tools/backups/pg-dump-rotate.sh); [restore-cluster.sh](../../../dev-tools/restores/restore-cluster.sh); [reset-service-db.sh](../../../dev-tools/restores/reset-service-db.sh); [smoke-backup-verifier-image.sh](../../../dev-tools/backups/smoke-backup-verifier-image.sh) | [verify-backups.sh](../../../dev-tools/backups/verify-backups.sh); [verify-backups-velero-contract.sh](../../../dev-tools/tests/verify-backups-velero-contract.sh); [verify-backups-cronjob-contract.sh](../../../dev-tools/tests/verify-backups-cronjob-contract.sh); [backup-verifier-image-contract.sh](../../../dev-tools/tests/backup-verifier-image-contract.sh); [reset-service-db-contract.sh](../../../dev-tools/tests/reset-service-db-contract.sh); [verify-restart-state.sh](../../../dev-tools/verify-restart-state.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The [Backup helper README](../../../dev-tools/backups/README.md) documents the helper boundaries. Measured verified-point RPO, immutable artifact and restore lineage, readable restore execution, environment-wide cold-start quarantine and reconciliation, post-restore trust reset, recovery-controller continuation, and controlled traffic reopen remain unimplemented or unproven. | | `PO-4.1` Logging, metrics, tracing, dashboards, and alerting | `partial` | `drift-found` | [ADR 0017](../../architecture/decisions/adr-0017-capability-gated-operational-tracing.md); [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md); [ADR 0167](../../architecture/decisions/adr-0167-allowlisted-sensitive-trace-attributes.md); [Logging/monitoring](../../architecture/system-architecture-logging-monitoring.md); [tracing](../../architecture/system-architecture-tracing.md) | [RuntimeIdentity.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [MetricsInterceptor.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/MetricsInterceptor.java); [GameplayWebSocketObservability.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [check-metrics-cardinality.py](../../../dev-tools/observability/check-metrics-cardinality.py); [validate-observability-contract.py](../../../dev-tools/observability/validate-observability-contract.py); [player-experience-smoke-runner-contract.sh](../../../dev-tools/tests/player-experience-smoke-runner-contract.sh); [GameplayWebSocketObservabilityTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservabilityTest.java) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player experience](./player-experience-commands-and-communication.md) | ADR 0017 level 1 (baseline observability) is the highest current advertisement: metrics and structured logs are the dependable surface, while generic RPC spans/export and trace-log correlation are best-effort. No named workflow has level-2 end-to-end proof; service-scoped sampling (level 3), tenant/game-instance/region sampling (level 4), broad region enrichment, embedded dashboards, and recovery-participant convergence observability remain unproved. The missing-source alert is fail-safe gap detection only and does not establish recovery readiness. The current profile overlays install only the applicable deadman rules; the player-flow canary and public-path blackbox alert families remain target-only and uninstalled pending deployment-owned gates. Capability-aware installation, deployment-owned external alert authority, atomic profile-transition cleanup, residual-series handling, and live proof remain implementation gaps. | -| `PO-4.2` Health, readiness, reliability policy, SLOs, and degraded operation | `partial`: dependency-readiness tracking and bounded gameplay/Telnet readiness gates are live; staged profile-aware SLO enforcement and complete control-action degradation partitions are not | `proven` for the named current readiness transition, health-indicator, admission, scheduler, and evidence-shape seams only; there is no executable proof of ADR 0160 enforceable SLO claims or ADR 0165 control-action failure modes | [Deployment preflight policy](../../architecture/system-architecture-deploy-preflight-policy.md); [logging and monitoring](../../architecture/system-architecture-logging-monitoring.md); [ADR 0160](../../architecture/decisions/adr-0160-staged-profile-aware-player-experience-slo-contract.md); [ADR 0165](../../architecture/decisions/adr-0165-authoritative-control-actions-during-observability-loss.md) | [DependencyReadinessSupport.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/health/DependencyReadinessSupport.java); [ReadinessTransitionTracker.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/health/ReadinessTransitionTracker.java); [GameplayPathReadinessHealthIndicator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [ReadinessTransitionTrackerTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/health/ReadinessTransitionTrackerTest.java); [GameplayPathReadinessHealthIndicatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java); [TelnetReadinessAdmissionIntegrationTest.java](../../../services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TelnetReadinessAdmissionIntegrationTest.java); [TickSchedulerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [player-experience-smoke-evidence-contract.sh](../../../dev-tools/tests/player-experience-smoke-evidence-contract.sh) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player access](./player-access-and-session.md) | Representative calibration, minimum-sample handling, enforceable SLO evidence, endpoint-class readiness, owner/audit sequencing, stable retry identity, isolation, and production-scale degraded-operation proof remain gaps. | +| `PO-4.2` Health, readiness, reliability policy, SLOs, and degraded operation | `partial`: dependency-readiness tracking and bounded gameplay/Telnet readiness gates are live; staged profile-aware SLO enforcement and complete control-action degradation partitions are not | `proven` for the previously named readiness transition, health-indicator, admission, scheduler, and evidence-shape seams only; the Game Session Ping-plus-HTTP dependency-readiness child has 70 passing focused client, indicator, configuration, and receiver tests plus successful YAML/Helm rendering and static checks; deployed readiness and genuine player `LOOK` remain `unrun`; there is no executable proof of ADR 0160 enforceable SLO claims or ADR 0165 control-action failure modes | [Deployment preflight policy](../../architecture/system-architecture-deploy-preflight-policy.md); [logging and monitoring](../../architecture/system-architecture-logging-monitoring.md); [ADR 0160](../../architecture/decisions/adr-0160-staged-profile-aware-player-experience-slo-contract.md); [ADR 0165](../../architecture/decisions/adr-0165-authoritative-control-actions-during-observability-loss.md) | [DependencyReadinessSupport.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/health/DependencyReadinessSupport.java); [ReadinessTransitionTracker.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/health/ReadinessTransitionTracker.java); [GameplayPathReadinessHealthIndicator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [ReadinessTransitionTrackerTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/health/ReadinessTransitionTrackerTest.java); [GameplayPathReadinessHealthIndicatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java); [TelnetReadinessAdmissionIntegrationTest.java](../../../services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TelnetReadinessAdmissionIntegrationTest.java); [TickSchedulerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [player-experience-smoke-evidence-contract.sh](../../../dev-tools/tests/player-experience-smoke-evidence-contract.sh) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player access](./player-access-and-session.md) | Representative calibration, minimum-sample handling, enforceable SLO evidence, endpoint-class readiness, owner/audit sequencing, stable retry identity, isolation, and production-scale degraded-operation proof remain gaps. | | `PO-4.3` Unit, integration, contract, static-analysis, and load verification | `partial`: deterministic repository unit, integration, contract, static-analysis, and bounded load-fixture seams exist; enforceable claims and production-like fault/load verification remain incomplete | `proven` for the named deterministic repository checks and bounded cross-service load fixture only; there is no current proof of enforceable claims or production-like fault/load behavior | [Testing](../../architecture/system-architecture-testing.md); [ADR 0174](../../architecture/decisions/adr-0174-maturity-scoped-protobuf-compatibility.md) | [build.gradle.kts](../../../build.gradle.kts); [ci.yml](../../../.github/workflows/ci.yml); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh); [check-flyway-versions.sh](../../../dev-tools/validation/check-flyway-versions.sh) | [gradle-proof-tooling-contract.sh](../../../dev-tools/tests/gradle-proof-tooling-contract.sh); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh); [check-flyway-versions.py](../../../dev-tools/validation/check-flyway-versions.py); [static-analysis-summary-contract.sh](../../../dev-tools/tests/static-analysis-summary-contract.sh); [MultiplayerLoadProofCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java) | All other trackers | Focused proof for enforceable claims, the maturity-scoped protobuf compatibility gate, and production-like fault/load behavior remains incomplete. | | `PO-4.4` Smoke, canary, incident evidence, and architecture conformance proof | `partial`: local smoke, restart/image entrypoints, the player-experience runner, and retained evidence-shape validation are live; independently scheduled synthetic canaries, asynchronous backend emit-and-query execution, and complete profile/event/fault evidence are not | `proven` for the current transport smoke, runner, and retained evidence-shape contracts only; there is no proof of a continuously scheduled hosted canary, supported-backend queryability, recovery-event-bound execution, or transport-complete acceptance | [Testing](../../architecture/system-architecture-testing.md); [player-experience runbook](../../architecture/system-architecture-player-experience-incident-runbook.md); [ADR 0161](../../architecture/decisions/adr-0161-profile-aware-isolated-synthetic-player-flow-canaries.md); [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md); [ADR 0164](../../architecture/decisions/adr-0164-three-boundary-profile-aware-verification-evidence.md); [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md) | [verify-fresh-bootstrap.sh](../../../dev-tools/verify-fresh-bootstrap.sh); [verify-restart-state.sh](../../../dev-tools/verify-restart-state.sh); [verify-smoke-images.sh](../../../dev-tools/verify-smoke-images.sh); [run-player-experience-smoke.py](../../../dev-tools/observability/run-player-experience-smoke.py); [validate-player-experience-smoke-evidence.py](../../../dev-tools/observability/validate-player-experience-smoke-evidence.py); [preview.yml](../../../.github/workflows/preview.yml); [dev-demo.yml](../../../.github/workflows/dev-demo.yml); [smoke-full.yml](../../../.github/workflows/smoke-full.yml) | [smoke-transport-contract.sh](../../../dev-tools/tests/smoke-transport-contract.sh); [player-experience-smoke-runner-contract.sh](../../../dev-tools/tests/player-experience-smoke-runner-contract.sh); [player-experience-smoke-evidence-contract.sh](../../../dev-tools/tests/player-experience-smoke-evidence-contract.sh); [architecture-doc-contracts.sh](../../../dev-tools/tests/architecture-doc-contracts.sh) | All other trackers | Hosted scheduling/queryability, evidence binding/freshness, profile/fault coverage, isolation, recovery-bound proof, and same-head-bound disposable preview proof for both required Telnet and deployed-browser public paths remain incomplete. | @@ -268,3 +268,9 @@ No competing target state is recorded for bounded metrics, curated edge routing, | `common-test-support` and gameplay test fixtures | Account runtime authority fakes, shared stack/baseline setup, transport drivers, transcript and eventual assertions | WebSocket/Telnet scenario helpers and cross-service proof contracts | | Logging & Admin | Operator/report/log-event and compatibility-read surfaces are current; admission-pointer reads/audit/prepared-upgrade proof reads are live, while mutation and target moderation workflows remain gated or unavailable. See [Logging & Admin runtime/data](../../architecture/microservices/logging-admin-service/runtime-and-data.md) and [moderation implementation status](../../architecture/microservices/logging-admin-service/moderation-policies.md#implementation-status). | REST/OpenAPI over owner-side runtime/control-plane contracts | | External monitor and observability tooling | Deadman authority, canary/blackbox evidence, alerts, and retained proof | Smoke signals, opaque external check references, and external liveness signal | + +### Game Session dependency-readiness repair + +The current child implementation replaces Game Session's synthetic player `ResolveLook` probe with an authenticated two-second `Ping` and the configured Game Logic actuator readiness endpoint through the shared bounded HTTP checker. Both must succeed alongside the existing Account and local store probes. Production URL binding is explicit and fail-closed; Kustomize and hosted shared configuration supply it. The canonical readiness contract remains in [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#readiness-and-liveness). + +Seventy focused client, indicator, configuration-binding, receiver and Game Logic INTERNAL_PROBE denial tests passed across qualified runs, with successful static checks, formatting and YAML/Helm rendering. Fresh packaged Game Session/Game Logic artifacts reached readiness and WebSocket LOGIN; PLAY stopped at an empty eligible catalog, so LOOK and Telnet were unrun in that packaged invocation. Deployed Kubernetes readiness remains unrun. This dependency-readiness proof establishes no canonical admitted `LOOK`, complete player-context convergence, genuine owner handoff or materialized World runtime. Game Logic's private World/Entity probes and player admission/routing guards remain unchanged. diff --git a/k8s/base/firemud-db-env.yaml b/k8s/base/firemud-db-env.yaml index 6fb0055236..26a5e4667e 100644 --- a/k8s/base/firemud-db-env.yaml +++ b/k8s/base/firemud-db-env.yaml @@ -5,6 +5,7 @@ metadata: namespace: firemud name: firemud-config data: + GAME_LOGIC_READINESS_URL: http://game-logic-service:8080/actuator/health/readiness FIREMUD_POSTGRES_HOST: postgres FIREMUD_POSTGRES_PORT: "5432" FIREMUD_POSTGRES_DB: firemud diff --git a/k8s/helm/firemud/values-hosted-shared.example.yaml b/k8s/helm/firemud/values-hosted-shared.example.yaml index fbdb8817bd..6e96ea3916 100644 --- a/k8s/helm/firemud/values-hosted-shared.example.yaml +++ b/k8s/helm/firemud/values-hosted-shared.example.yaml @@ -81,6 +81,7 @@ previewStack: storageClassName: local-path sharedConfig: + GAME_LOGIC_READINESS_URL: http://game-logic-service:8080/actuator/health/readiness FIREMUD_POSTGRES_HOST: postgres FIREMUD_POSTGRES_PORT: "5432" FIREMUD_POSTGRES_DB: firemud diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java index 988eb4b290..35f5984754 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java @@ -135,6 +135,83 @@ public net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence readComm return committed; } + /** + * Qualifies the immutable receipt through committed owners without resolving or writing a + * descriptor. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CommittedReceipt readCommittedReceipt( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt + receipt) { + readCommittedCreation(receipt.creationEvidence()); + var source = receipt.sourceEvidence(); + var committed = + sourceRepository + .read( + source.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.targetNamespace()) + .orElseThrow(() -> new IllegalStateException("Committed fixture source unavailable")); + if (!source.equals(committed)) { + throw new IllegalStateException("Immutable fixture receipt differs from committed source"); + } + var launch = receipt.launchReadEvidence(); + Snapshot current = + snapshot( + source.sourceGameRowId(), + launch.gameTemplateId(), + launch.versionState().getVersionId(), + committed); + if (!current.bundleProto().equals(launch.publishedReleaseBundle()) + || !current.artifactProto().equals(launch.versionAssetArtifactState()) + || !current.versionProto().equals(launch.versionState())) { + throw new IllegalStateException( + "Immutable fixture receipt differs from committed launch snapshots"); + } + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + source.targetNamespace(), + receipt.fixtureOperationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + launch.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + var expected = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .fromLaunchDescriptorMessage(request, launch.launchDescriptor()); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(request.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(request.controlPlaneRequestId())); + ResolvedLaunchDescriptorDto descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + request.canonicalTenantId(), + request.worldSlug(), + request.controlPlaneRequestId(), + expected.requestDigest(), + expected.resultDigest()); + if (!expected.equals(descriptor.authoredWorldBinding())) { + throw new IllegalStateException( + "Immutable fixture receipt differs from committed descriptor"); + } + requireDescriptorMatchesSnapshot(descriptor, request, current); + return new CommittedReceipt(current, descriptor); + } + + public record CommittedReceipt(Snapshot snapshot, ResolvedLaunchDescriptorDto descriptor) {} + /** Resolves and independently reads the committed descriptor outside the seeder transaction. */ @Transactional(propagation = Propagation.NOT_SUPPORTED) public ResolvedLaunchDescriptorDto resolveAndReadLaunchDescriptor( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java new file mode 100644 index 0000000000..b4461d154c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorization.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.gamedesign.data; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.file.Path; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; + +/** Fixed operation authorization backed by preexisting producer owners; not a wire issuer. */ +@Service +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public class RunOwnedFixtureOwnerReadAuthorization { + private final RunOwnedFixtureLaunchReadback readback; + private final RunOwnedFixturePolicyProducer policy; + private final String namespace; + private final String runId; + private final String project; + private final String capabilityPath; + private final String receiptPath; + private final String sessionCertificate; + private final String worldCertificate; + private final String caCertificate; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Framework-managed owner collaborators are retained; invalid immutable fixture configuration intentionally refuses startup.") + public RunOwnedFixtureOwnerReadAuthorization( + RunOwnedFixtureLaunchReadback readback, + RunOwnedFixturePolicyProducer policy, + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String project, + @Value( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:/app/run-owned-initial-admission-capability.json}") + String capabilityPath, + @Value( + "${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:/app/run-owned-authored-world-source/source-receipt.json}") + String receiptPath, + @Value("${FIREMUD_SMOKE_GAME_SESSION_LEAF_CERT_PATH:/app/game-session-fixture-client.crt}") + String sessionCertificate, + @Value( + "${FIREMUD_SMOKE_WORLD_MANAGEMENT_LEAF_CERT_PATH:/app/world-management-fixture-client.crt}") + String worldCertificate, + @Value("${firemud.grpc.ca-cert:certs/ca.crt}") String caCertificate) { + this.readback = Objects.requireNonNull(readback); + this.policy = Objects.requireNonNull(policy); + this.namespace = namespace; + this.runId = runId; + this.project = project; + this.capabilityPath = capabilityPath; + this.receiptPath = receiptPath; + this.sessionCertificate = sessionCertificate; + this.worldCertificate = worldCertificate; + this.caCertificate = caCertificate; + // Receipt publication happens after startup seeding. Configuration/certificates must already + // be valid, while missing or uncommitted receipt evidence is refused at every actual read. + configuration(); + } + + public SourceReceipt authorizeSource(ResolveAuthoredWorldSourceRequest wire) { + var trusted = authenticatedConfiguration(); + SourceReceipt receipt = receipt(trusted); + final AuthoredWorldSourceGrpcCodec.ReadRequest request; + try { + request = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, wire); + } catch (IllegalArgumentException invalidRequest) { + throw new RequestDecodingException(invalidRequest); + } + var source = receipt.sourceEvidence(); + if (!request.targetNamespace().equals(source.targetNamespace()) + || !request.operationId().equals(source.operationId()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug())) { + throw new SecurityException("Fixed fixture source selector differs"); + } + qualifyOwners(trusted, receipt); + return receipt; + } + + public SourceReceipt authorizeVersion(GetAuthoredWorldVersionStateRequest wire) { + var trusted = authenticatedConfiguration(); + SourceReceipt receipt = receipt(trusted); + final AuthoredWorldVersionStateEvidence.Request request; + try { + request = AuthoredWorldVersionStateGrpcCodec.fromRequest(wire); + } catch (IllegalArgumentException invalidRequest) { + throw new RequestDecodingException(invalidRequest); + } + var source = receipt.sourceEvidence(); + if (!namespace.equals(request.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug()) + || !request.sourceOperationId().equals(source.operationId()) + || !request.expectedSourceEvidenceDigest().equals(source.evidenceDigest()) + || request.versionId() != receipt.launchReadEvidence().versionState().getVersionId()) { + throw new SecurityException("Fixed fixture Version selector differs"); + } + qualifyOwners(trusted, receipt); + return receipt; + } + + private TestDataSeeder.FixtureCapability authenticatedConfiguration() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException("Fixture owner reads reject caller context"); + } + var peer = GrpcPeerIdentity.current(); + var certificate = GrpcPeerCertificateEvidence.current(); + if (peer == null + || certificate == null + || !peer.uri().equals("spiffe://firemud/ns/dev/sa/world-management-service")) { + throw new SecurityException("Fixed World TLS peer required"); + } + var trusted = configuration(); + if (!peer.isInNamespace(namespace) + || !certificate.leafSha256().equals(trusted.worldManagementLeafSha256())) { + throw new SecurityException("Fixed World TLS leaf differs"); + } + return trusted; + } + + private TestDataSeeder.FixtureCapability configuration() { + return TestDataSeeder.verifyFixtureConfiguration( + namespace, + runId, + project, + capabilityPath, + receiptPath, + sessionCertificate, + worldCertificate, + caCertificate); + } + + private SourceReceipt receipt(TestDataSeeder.FixtureCapability trusted) { + byte[] bytes = + RunOwnedFixtureImmutableFileReader.readBoundedImmutableFile( + Path.of(receiptPath), + 16 * 1024, + () -> new IllegalStateException("Fixed fixture receipt unavailable")); + try { + return RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(bytes, trusted.wire()); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Fixed fixture receipt invalid", invalid); + } + } + + private void qualifyOwners(TestDataSeeder.FixtureCapability trusted, SourceReceipt receipt) { + var committed = readback.readCommittedReceipt(receipt); + var actualSeal = + policy.readExisting( + trusted, receipt.creationEvidence(), committed.snapshot(), committed.descriptor()); + if (!actualSeal.equals(receipt.fixturePolicySeal())) { + throw new IllegalStateException("Fixed receipt policy seal differs from committed owner"); + } + } + + /** Marks only malformed wire requests; owner-side argument failures have different semantics. */ + public static final class RequestDecodingException extends IllegalArgumentException { + public RequestDecodingException(IllegalArgumentException cause) { + super("Fixture owner request could not be decoded", cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java index b3040cc534..80fcd3303b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.data; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; @@ -29,7 +30,11 @@ public final class RunOwnedFixturePolicyProducer { private final TransactionTemplate write; private final TransactionTemplate read; - RunOwnedFixturePolicyProducer( + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Framework-managed SQL and JSON collaborators are retained for owner operations.") + public RunOwnedFixturePolicyProducer( DSLContext dsl, RunOwnedFixtureLaunchReadback readback, ObjectMapper json, @@ -51,6 +56,85 @@ RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal sealAndRead( FreshTenantCreationEvidence creation, RunOwnedFixtureLaunchReadback.Snapshot snapshot, ResolvedLaunchDescriptorDto descriptor) { + PolicyFrame frame = frame(trusted, creation, snapshot, descriptor); + var source = snapshot.sourceEvidence(); + byte[] request = frame.request(); + String requestDigest = frame.requestDigest(); + String bindingJson = frame.bindingJson(); + String policyJson = frame.policyJson(); + write.executeWithoutResult( + ignored -> { + dsl.fetchSingle( + "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", + creation.sourceGameRowId(), + creation.sourceGameTenantKey()); + dsl.fetchSingle( + "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", + snapshot.version().id(), + creation.sourceGameTenantKey()); + UUID operationId = trusted.operationId(); + String evidenceDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + operationId, requestDigest); + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " + + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " + + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + source.canonicalTenantId(), + snapshot.version().canonicalVersionId(), + snapshot.version().id(), + snapshot.version().versionNumber(), + operationId, + request, + requestDigest, + evidenceDigest, + bindingJson, + policyJson); + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); + }); + var seal = + Objects.requireNonNull( + read.execute( + ignored -> + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); + // Independent owner read after seal commit; changing upstream rows cannot publish a receipt. + readback.readCommittedCreation(creation); + var committedSnapshot = readback.readCommittedOutcome(snapshot); + var committedDescriptor = + readback.resolveAndReadLaunchDescriptor(descriptor.authoredWorldBinding().request()); + if (!descriptor.equals(committedDescriptor)) { + throw new IllegalStateException("Fixture descriptor changed after policy seal commit"); + } + readback.requireDescriptorMatchesSnapshot( + committedDescriptor, descriptor.authoredWorldBinding().request(), committedSnapshot); + return seal; + } + + /** Reads only an already sealed fixture owner; never invokes the producer write transaction. */ + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal readExisting( + TestDataSeeder.FixtureCapability trusted, + FreshTenantCreationEvidence creation, + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + ResolvedLaunchDescriptorDto descriptor) { + PolicyFrame frame = frame(trusted, creation, snapshot, descriptor); + return Objects.requireNonNull( + read.execute( + ignored -> + requireExactRow( + snapshot, + frame.request(), + frame.requestDigest(), + frame.bindingJson(), + frame.policyJson()))); + } + + private PolicyFrame frame( + TestDataSeeder.FixtureCapability trusted, + FreshTenantCreationEvidence creation, + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + ResolvedLaunchDescriptorDto descriptor) { var capability = trusted.wire(); var source = snapshot.sourceEvidence(); if (!creation.canonicalTenantId().equals(source.canonicalTenantId()) @@ -110,54 +194,19 @@ RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal sealAndRead( Map.entry("ownerAccountId", capability.ownerAccountId())); String bindingJson = serialize(binding); String policyJson = serialize(policy); - write.executeWithoutResult( - ignored -> { - dsl.fetchSingle( - "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", - creation.sourceGameRowId(), - creation.sourceGameTenantKey()); - dsl.fetchSingle( - "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", - snapshot.version().id(), - creation.sourceGameTenantKey()); - UUID operationId = trusted.operationId(); - String evidenceDigest = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - operationId, requestDigest); - dsl.execute( - "INSERT INTO game_design_published_realm_policy_set " - + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " - + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " - + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " - + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", - source.canonicalTenantId(), - snapshot.version().canonicalVersionId(), - snapshot.version().id(), - snapshot.version().versionNumber(), - operationId, - request, - requestDigest, - evidenceDigest, - bindingJson, - policyJson); - requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); - }); - var seal = - Objects.requireNonNull( - read.execute( - ignored -> - requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); - // Independent owner read after seal commit; changing upstream rows cannot publish a receipt. - readback.readCommittedCreation(creation); - var committedSnapshot = readback.readCommittedOutcome(snapshot); - var committedDescriptor = - readback.resolveAndReadLaunchDescriptor(descriptor.authoredWorldBinding().request()); - if (!descriptor.equals(committedDescriptor)) { - throw new IllegalStateException("Fixture descriptor changed after policy seal commit"); + return new PolicyFrame(request, requestDigest, bindingJson, policyJson); + } + + private record PolicyFrame( + byte[] request, String requestDigest, String bindingJson, String policyJson) { + private PolicyFrame { + request = request.clone(); + } + + @Override + public byte[] request() { + return request.clone(); } - readback.requireDescriptorMatchesSnapshot( - committedDescriptor, descriptor.authoredWorldBinding().request(), committedSnapshot); - return seal; } private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactRow( @@ -173,6 +222,9 @@ private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactR snapshot.sourceEvidence().canonicalTenantId(), snapshot.version().canonicalVersionId()); if (row == null + || !snapshot.version().id().equals(row.get("game_design_version_row_id", Long.class)) + || !Integer.toString(snapshot.version().versionNumber()) + .equals(row.get("version_number", String.class)) || !Boolean.TRUE.equals(row.get("sealed", Boolean.class)) || row.get("fixture_operation_id", UUID.class) == null || !Arrays.equals(request, row.get("fixture_request_bytes", byte[].class)) @@ -182,6 +234,26 @@ private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactR throw new IllegalStateException( "Fixture policy seal differs from its exact original evidence"); } + for (String humanField : + java.util.List.of( + "source_commit_id", + "source_epoch", + "target_proof_json", + "operation_bytes", + "capture_bytes", + "terminal_evidence_bytes", + "release_content_bytes", + "published_release_bundle_ref", + "published_release_bundle_digest", + "publish_workflow_id", + "manifest_hash", + "publication_version_state_epoch", + "policy_count", + "policy_set_digest")) { + if (row.get(humanField) != null) { + throw new IllegalStateException("Fixture policy owner contains mixed Human evidence"); + } + } UUID operation = row.get("fixture_operation_id", UUID.class); if (!operation .toString() diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index 3df85ac74f..ca3c7408bd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -526,6 +526,27 @@ public void afterCommit() { } private FixtureCapability loadFixtureCapability() { + return verifyFixtureConfiguration( + workloadNamespace, + fixtureRunId, + fixtureComposeProjectName, + fixtureCapabilityPath, + fixtureReceiptPath, + gameSessionLeafCertPath, + worldManagementLeafCertPath, + caCertPath); + } + + /** The producer and fixed read adapters share the exact immutable configuration verifier. */ + static FixtureCapability verifyFixtureConfiguration( + String workloadNamespace, + String fixtureRunId, + String fixtureComposeProjectName, + String fixtureCapabilityPath, + String fixtureReceiptPath, + String gameSessionLeafCertPath, + String worldManagementLeafCertPath, + String caCertPath) { if (!FIXTURE_NAMESPACE.equals(workloadNamespace) || !safeFixtureId(fixtureRunId) || !safeFixtureId(fixtureComposeProjectName) @@ -735,7 +756,7 @@ private void requireExistingReceipt(Path destination, byte[] expected) throws IO } } - private byte[] readBoundedImmutableFile(Path path, String fileDescription) { + private static byte[] readBoundedImmutableFile(Path path, String fileDescription) { return RunOwnedFixtureImmutableFileReader.readBoundedImmutableFile( path, MAX_FIXTURE_FILE_BYTES, @@ -743,7 +764,7 @@ private byte[] readBoundedImmutableFile(Path path, String fileDescription) { new IllegalStateException("Run-owned fixture " + fileDescription + " file is invalid")); } - private X509Certificate readCertificate(Path path) { + private static X509Certificate readCertificate(Path path) { try { byte[] bytes = readBoundedImmutableFile(path, "TLS certificate"); return (X509Certificate) @@ -755,7 +776,7 @@ private X509Certificate readCertificate(Path path) { } } - private void requireCertificatePins( + private static void requireCertificatePins( X509Certificate gameSessionCertificate, X509Certificate worldManagementCertificate, X509Certificate caCertificate, @@ -778,7 +799,7 @@ private void requireCertificatePins( "World Management"); } - private void requireRecipientCertificatePins( + private static void requireRecipientCertificatePins( X509Certificate recipientCertificate, X509Certificate caCertificate, String expectedLeafDigest, @@ -814,19 +835,19 @@ private void requireRecipientCertificatePins( } } - private String sha256(byte[] bytes) throws Exception { + private static String sha256(byte[] bytes) throws Exception { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } - private boolean safeFixtureId(String value) { + private static boolean safeFixtureId(String value) { return value != null && value.matches("[a-z0-9][a-z0-9-]{0,127}"); } - private boolean absolutePath(String value) { + private static boolean absolutePath(String value) { return value != null && !value.isBlank() && Path.of(value).isAbsolute(); } - private boolean validCapabilityPath(String value) { + private static boolean validCapabilityPath(String value) { if (!absolutePath(value)) { return false; } @@ -835,7 +856,7 @@ private boolean validCapabilityPath(String value) { && "run-owned-initial-admission-capability.json".equals(fileName.toString()); } - private boolean validReceiptPath(String value) { + private static boolean validReceiptPath(String value) { if (!absolutePath(value)) { return false; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java index 9b01b0ca02..ca66a01436 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -13,8 +13,10 @@ import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.TransactionException; /** Standalone exact authored-source owner read; deliberately not registered as a gRPC service. */ public final class AuthoredWorldSourceReadGrpcService @@ -70,40 +72,13 @@ public void resolveAuthoredWorldSource( .withDescription("Authored-world source evidence is incomplete or inconsistent") .asRuntimeException()); return; - } catch (DataAccessResourceFailureException - | TransientDataAccessException - | org.springframework.transaction.TransactionException exception) { - responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Authored-world source evidence is temporarily unavailable") - .asRuntimeException()); - return; - } catch (org.springframework.dao.DataAccessException exception) { - Status.Code code = - hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; - responseObserver.onError( - Status.fromCode(code) - .withDescription( - code == Status.Code.UNAVAILABLE - ? "Authored-world source evidence is temporarily unavailable" - : "Authored-world source evidence could not be read") - .asRuntimeException()); - return; - } catch (org.jooq.exception.DataAccessException exception) { - Status.Code code = - hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; - responseObserver.onError( - Status.fromCode(code) - .withDescription( - code == Status.Code.UNAVAILABLE - ? "Authored-world source evidence is temporarily unavailable" - : "Authored-world source evidence could not be read") - .asRuntimeException()); - return; } catch (RuntimeException exception) { + Status storageStatus = storageFailureStatus(exception); responseObserver.onError( - Status.INTERNAL - .withDescription("Authored-world source evidence could not be read") + (storageStatus == null + ? Status.INTERNAL.withDescription( + "Authored-world source evidence could not be read") + : storageStatus) .asRuntimeException()); return; } @@ -129,6 +104,38 @@ public void resolveAuthoredWorldSource( responseObserver.onCompleted(); } + /** Returns the existing owner storage classification, or {@code null} for non-storage errors. */ + static Status storageFailureStatus(Throwable failure) { + if (failure instanceof TransactionException) { + boolean retryable = + (failure instanceof org.springframework.transaction.CannotCreateTransactionException + && !(failure + instanceof + org.springframework.transaction.NestedTransactionNotSupportedException)) + || failure instanceof org.springframework.transaction.TransactionTimedOutException; + return Status.fromCode(retryable ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL) + .withDescription( + retryable + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read"); + } + if (failure instanceof DataAccessResourceFailureException + || failure instanceof TransientDataAccessException) { + return Status.UNAVAILABLE.withDescription( + "Authored-world source evidence is temporarily unavailable"); + } + if (failure instanceof DataAccessException + || failure instanceof org.jooq.exception.DataAccessException) { + boolean connectionFailure = hasConnectionFailureSqlState(failure); + return Status.fromCode(connectionFailure ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL) + .withDescription( + connectionFailure + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read"); + } + return null; + } + private boolean isWorldManagementPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null @@ -137,7 +144,7 @@ private boolean isWorldManagementPeer() { .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); } - private static boolean hasConnectionFailureSqlState(Throwable failure) { + static boolean hasConnectionFailureSqlState(Throwable failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof SQLException exception) { String sqlState = exception.getSQLState(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java index 338defa01c..eef3178b22 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -107,9 +107,13 @@ public void getAuthoredWorldVersionState( : "Game Design owner storage could not be read") .asRuntimeException()); } catch (TransactionException exception) { + Status storageStatus = AuthoredWorldSourceReadGrpcService.storageFailureStatus(exception); responseObserver.onError( - Status.UNAVAILABLE - .withDescription("Game Design owner snapshot is temporarily unavailable") + storageStatus + .withDescription( + storageStatus.getCode() == Status.Code.UNAVAILABLE + ? "Game Design owner snapshot is temporarily unavailable" + : "Game Design owner snapshot could not be read") .asRuntimeException()); } catch (IllegalStateException exception) { responseObserver.onError( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java new file mode 100644 index 0000000000..58fce2e750 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldSourceReadGrpcService.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; + +/** Fixed-fixture registration of the existing standalone source owner kernel. */ +@GrpcService +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public final class RunOwnedFixtureAuthoredWorldSourceReadGrpcService + extends AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceImplBase { + private final RunOwnedFixtureOwnerReadAuthorization authorization; + private final AuthoredWorldSourceReadGrpcService kernel; + private final String namespace; + + public RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + RunOwnedFixtureOwnerReadAuthorization authorization, + GameAuthoredWorldSourceRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + this.authorization = authorization; + this.namespace = namespace; + this.kernel = new AuthoredWorldSourceReadGrpcService(repository, namespace); + } + + @Override + public void resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest request, + StreamObserver observer) { + try { + var receipt = authorization.authorizeSource(request); + final AuthoredWorldSourceGrpcCodec.ReadRequest expected; + try { + expected = AuthoredWorldSourceGrpcCodec.fromReadRequest(namespace, request); + } catch (IllegalArgumentException invalidRequest) { + throw new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException(invalidRequest); + } + kernel.resolveAuthoredWorldSource( + request, + new StreamObserver<>() { + private ResolveAuthoredWorldSourceResponse result; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse value) { + result = value; + } + + @Override + public void onError(Throwable error) { + observer.onError(error); + } + + @Override + public void onCompleted() { + try { + var source = AuthoredWorldSourceGrpcCodec.fromReadResponse(expected, result); + if (!source.equals(receipt.sourceEvidence())) { + throw new IllegalStateException( + "Committed source changed after fixture qualification"); + } + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact committed fixture source unavailable") + .asRuntimeException()); + } + } + }); + } catch (SecurityException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Fixed World fixture read denied") + .asRuntimeException()); + } catch (RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Closed fixture source request required") + .asRuntimeException()); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed fixture authority does not match the request") + .asRuntimeException()); + } catch (RuntimeException failure) { + Status storageStatus = AuthoredWorldSourceReadGrpcService.storageFailureStatus(failure); + observer.onError( + (storageStatus != null + ? storageStatus + : Status.FAILED_PRECONDITION.withDescription( + "Committed fixture authority unavailable")) + .asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java new file mode 100644 index 0000000000..bcf970e475 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldVersionStateGrpcService.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.PlatformTransactionManager; + +/** Fixed-fixture registration of the existing standalone source-qualified Version kernel. */ +@GrpcService +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public final class RunOwnedFixtureAuthoredWorldVersionStateGrpcService + extends AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceImplBase { + private final RunOwnedFixtureOwnerReadAuthorization authorization; + private final AuthoredWorldVersionStateGrpcService kernel; + + public RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + RunOwnedFixtureOwnerReadAuthorization authorization, + PlatformTransactionManager transactions, + GameAuthoredWorldSourceRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + this.authorization = authorization; + this.kernel = + new AuthoredWorldVersionStateGrpcService( + new AuthoredWorldVersionStateService(transactions, repository), namespace); + } + + @Override + public void getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest request, + StreamObserver observer) { + try { + var receipt = authorization.authorizeVersion(request); + final AuthoredWorldVersionStateEvidence.Request expected; + try { + expected = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalidRequest) { + throw new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException(invalidRequest); + } + kernel.getAuthoredWorldVersionState( + request, + new StreamObserver<>() { + private GetAuthoredWorldVersionStateResponse result; + + @Override + public void onNext(GetAuthoredWorldVersionStateResponse value) { + result = value; + } + + @Override + public void onError(Throwable error) { + observer.onError(error); + } + + @Override + public void onCompleted() { + try { + var evidence = AuthoredWorldVersionStateGrpcCodec.fromResponse(expected, result); + var launch = receipt.launchReadEvidence(); + if (!evidence.sourceEvidence().equals(receipt.sourceEvidence()) + || !evidence + .canonicalVersionId() + .equals( + UUID.fromString( + launch.publishedReleaseBundle().getCanonicalVersionId())) + || evidence.versionState() != launch.versionState().getVersionState() + || evidence.versionStateEpoch() + != launch.versionState().getVersionStateEpoch()) { + throw new IllegalStateException( + "Committed Version changed after fixture qualification"); + } + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact committed fixture Version unavailable") + .asRuntimeException()); + } + } + }); + } catch (SecurityException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Fixed World fixture read denied") + .asRuntimeException()); + } catch (RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Closed fixture Version request required") + .asRuntimeException()); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed fixture authority does not match the request") + .asRuntimeException()); + } catch (RuntimeException failure) { + Status storageStatus = AuthoredWorldSourceReadGrpcService.storageFailureStatus(failure); + if (storageStatus != null) { + storageStatus = + storageStatus.withDescription( + storageStatus.getCode() == Status.Code.UNAVAILABLE + ? "Game Design Version state is temporarily unavailable" + : "Game Design Version state could not be read"); + } + observer.onError( + (storageStatus != null + ? storageStatus + : Status.FAILED_PRECONDITION.withDescription( + "Committed fixture authority unavailable")) + .asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 5f2bc1c4f4..2c82a2710e 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -56,6 +56,8 @@ firemud: - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor - gamedesign.v1.GameDesignService/GetLaunchDescriptor - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding + - gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource + - gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index aba342b57e..7272e16f83 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -67,6 +67,8 @@ firemud: - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor - gamedesign.v1.GameDesignService/GetLaunchDescriptor - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding + - gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource + - gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java new file mode 100644 index 0000000000..dfd63e52e0 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java @@ -0,0 +1,654 @@ +package net.firedevops.firemud.gamedesign.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +public abstract class TestDataSeederIntegrationSupport { + protected static final String NAMESPACE = "dev"; + protected static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; + protected static final String WORLD_MANAGEMENT_URI_SAN = + "spiffe://firemud/ns/dev/sa/world-management-service"; + protected static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + protected static final Table SOURCE_DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + protected static final Field REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + protected static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + protected static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + + @Container + protected static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @DynamicPropertySource + protected static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired protected TestDataSeeder seeder; + + @Autowired + protected net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService + gameDesignGrpcService; + + @MockitoSpyBean + protected net.firedevops.firemud.gamedesign.data.RunOwnedFixtureLaunchReadback fixtureReadback; + + @MockitoSpyBean + protected net.firedevops.firemud.gamedesign.data.RunOwnedFixturePolicyProducer fixturePolicy; + + @Autowired protected Flyway flyway; + @Autowired protected ConfigurableEnvironment environment; + @MockitoSpyBean protected GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired protected GameRepository gameRepository; + + @Autowired + protected net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; + + @Autowired protected GameTemplateRepository templateRepository; + @Autowired protected VersionRepository versionRepository; + @Autowired protected VersionAssetArtifactRepository artifactRepository; + @Autowired protected VersionService versionService; + @Autowired protected VersionAssetArtifactService artifactService; + @Autowired protected LaunchDescriptorRepository launchDescriptorRepository; + @MockitoSpyBean protected LaunchDescriptorService launchDescriptorService; + @Autowired protected PlatformTransactionManager transactionManager; + @Autowired protected DSLContext dsl; + @Autowired protected ObjectMapper objectMapper; + + @BeforeEach + protected void resetDisposableServiceSchema() { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + flyway.clean(); + flyway.migrate(); + seeder.run(new DefaultApplicationArguments(new String[] {})); + } + + protected static void assertSocketReadDenied(Runnable read) { + assertThatThrownBy(read::run) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + protected void withFixedReadClients( + Server server, + Fixture fixture, + Path certificate, + Path privateKey, + BiConsumer reads) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + server.getPort()); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(fixture.caCertificatePath().toString()); + var channels = new CopyOnWriteArrayList(); + var factory = + new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int port, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial material) + throws javax.net.ssl.SSLException { + ManagedChannel channel = + super.buildChannel(target, port, properties, keepAlive, material); + channels.add(channel); + return channel; + } + }; + try (var sourceClient = new AuthoredWorldSourceClient(endpoints, tls, factory, NAMESPACE); + var versionClient = + new AuthoredWorldVersionStateClient(endpoints, tls, factory, NAMESPACE)) { + sourceClient.init(); + versionClient.init(); + reads.accept(sourceClient, versionClient); + } finally { + for (ManagedChannel channel : channels) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } + + protected FixedReadLeaf issueFixedReadLeaf( + Fixture fixture, String name, String uri, boolean server) throws Exception { + Path directory = java.util.Objects.requireNonNull(fixture.caCertificatePath().getParent()); + Path key = directory.resolve(name + ".key"); + Path csr = directory.resolve(name + ".csr"); + Path certificate = directory.resolve(name + ".crt"); + Path extensions = directory.resolve(name + ".ext"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + key.toString(), + "-out", + csr.toString(), + "-subj", + "/CN=" + name); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=" + + (server ? "serverAuth" : "clientAuth") + + "\n" + + "subjectAltName=URI:" + + uri + + (server + ? ",DNS:game-design-service,DNS:game-design-service.dev,DNS:game-design-service.dev.svc,DNS:game-design-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + : ",DNS:world-management-service") + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + csr.toString(), + "-CA", + fixture.caCertificatePath().toString(), + "-CAkey", + directory.resolve("ca.key").toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + Files.setPosixFilePermissions( + certificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + awaitFixtureCertificatesValid(certificate); + return new FixedReadLeaf(certificate, key); + } + + protected record FixedReadLeaf(Path certificate, Path privateKey) { + public FixedReadLeaf {} + } + + protected Map fixedReadOwnerRows() { + Map rows = new LinkedHashMap<>(); + for (String table : + Set.of( + "game_tenant_creation_operations", + "game_design_authored_world_source_operations", + "game_design_authored_world_source_deliveries", + "game", + "game_templates", + "version", + "version_asset_artifact", + "published_release_bundle", + "launch_descriptor", + "game_design_published_realm_policy_set", + "game_design_realm_policy_capture", + "game_design_publication_operation", + "game_design_published_realm_policy")) { + rows.put( + table, + dsl.fetch( + "SELECT row_to_json(t)::text AS bytes, xmin::text AS row_version FROM " + + table + + " t ORDER BY row_to_json(t)::text") + .formatJSON()); + } + return rows; + } + + protected Set fieldNames(JsonNode object) { + Set fields = new HashSet<>(); + object.propertyNames().forEach(fields::add); + return fields; + } + + protected byte[] readPublishedReleaseBundleBytes() { + Record row = + dsl.fetchOne( + "select convert_to(row_to_json(release_bundle)::text, 'UTF8') as bundle_bytes " + + "from published_release_bundle as release_bundle " + + "where tenant_id = ? and version_id = ?", + "1", + 1L); + assertThat(row).isNotNull(); + return row.get("bundle_bytes", byte[].class); + } + + protected void writeVersionStateEpoch( + TransactionTemplate transaction, String tenantId, Long versionId, long epoch) { + transaction.executeWithoutResult( + status -> { + int updated = + dsl.execute( + "update version set version_state_epoch = ? where tenant_id = ? and id = ?", + epoch, + tenantId, + versionId); + assertThat(updated).isOne(); + }); + } + + protected Fixture prepareFixture(Path testDirectory) throws Exception { + return prepareFixture(testDirectory, true); + } + + protected Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwner) + throws Exception { + Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); + Path caKey = certificateDirectory.resolve("ca.key"); + Path caCertificate = certificateDirectory.resolve("ca.crt"); + Path sessionKey = certificateDirectory.resolve("game-session.key"); + Path sessionRequest = certificateDirectory.resolve("game-session.csr"); + Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); + Path sessionExtensions = certificateDirectory.resolve("game-session.ext"); + Path worldManagementKey = certificateDirectory.resolve("world-management.key"); + Path worldManagementRequest = certificateDirectory.resolve("world-management.csr"); + Path worldManagementCertificate = certificateDirectory.resolve("world-management.crt"); + Path worldManagementExtensions = certificateDirectory.resolve("world-management.ext"); + runOpenSsl( + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-days", + "2", + "-keyout", + caKey.toString(), + "-out", + caCertificate.toString(), + "-subj", + "/CN=FireMUD test fixture CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + sessionKey.toString(), + "-out", + sessionRequest.toString(), + "-subj", + "/CN=game-session-service"); + Files.writeString( + sessionExtensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth,serverAuth\n" + + "subjectAltName=URI:" + + SESSION_URI_SAN + + ",DNS:game-session-service" + + ",DNS:game-session-service.dev" + + ",DNS:game-session-service.dev.svc" + + ",DNS:game-session-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + sessionRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + sessionCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + sessionExtensions.toString()); + runOpenSsl( + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-sha256", + "-keyout", + worldManagementKey.toString(), + "-out", + worldManagementRequest.toString(), + "-subj", + "/CN=world-management-service"); + Files.writeString( + worldManagementExtensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=clientAuth,serverAuth\n" + + "subjectAltName=URI:" + + WORLD_MANAGEMENT_URI_SAN + + ",DNS:world-management-service" + + ",DNS:world-management-service.dev" + + ",DNS:world-management-service.dev.svc" + + ",DNS:world-management-service.dev.svc.cluster.local,DNS:localhost,IP:127.0.0.1" + + "\n"); + runOpenSsl( + "x509", + "-req", + "-in", + worldManagementRequest.toString(), + "-CA", + caCertificate.toString(), + "-CAkey", + caKey.toString(), + "-CAcreateserial", + "-out", + worldManagementCertificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + worldManagementExtensions.toString()); + Files.setPosixFilePermissions( + caCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + sessionCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.setPosixFilePermissions( + worldManagementCertificate, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + String leafDigest = certificateDigest(sessionCertificate); + String worldManagementLeafDigest = certificateDigest(worldManagementCertificate); + String caDigest = certificateDigest(caCertificate); + String runId = "fixture-commit-proof"; + String composeProjectName = "firemud-smoke-fixture-commit-proof"; + String claimDigest = "e".repeat(64); + UUID operationId = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .fixtureOperationId(claimDigest, runId, composeProjectName, leafDigest, caDigest); + Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); + Map capability = new LinkedHashMap<>(); + capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); + capability.put("runId", runId); + capability.put("composeProjectName", composeProjectName); + capability.put("claimDigest", claimDigest); + capability.put("operationId", operationId.toString()); + capability.put("tenantId", 1); + capability.put( + "gameTemplateId", + templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow().getId()); + capability.put("ownerAccountId", 1); + capability.put("worldSlug", "demo"); + capability.put("worldDisplayName", "Demo World"); + capability.put("realmSlug", "production"); + capability.put("realmDisplayName", "Live Realm"); + capability.put("visible", true); + capability.put("publicProductionRealm", true); + capability.put("requiresCharacterSelection", false); + capability.put("stateScope", "SHARED"); + capability.put("characterCreationPolicy", "ALLOW_NEW"); + capability.put("gameSessionLeafSha256", leafDigest); + capability.put("gameSessionUriSan", SESSION_URI_SAN); + capability.put("worldManagementLeafSha256", worldManagementLeafDigest); + capability.put("worldManagementUriSan", WORLD_MANAGEMENT_URI_SAN); + capability.put("caCertificateSha256", caDigest); + Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); + Files.setPosixFilePermissions( + capabilityPath, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + awaitFixtureCertificatesValid(sessionCertificate, worldManagementCertificate, caCertificate); + + Path receiptDirectory = + Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); + Files.setPosixFilePermissions( + receiptDirectory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.OTHERS_EXECUTE)); + Fixture fixture = + new Fixture( + operationId, + runId, + composeProjectName, + capabilityPath, + receiptDirectory.resolve("source-receipt.json"), + sessionCertificate, + worldManagementCertificate, + caCertificate, + leafDigest, + worldManagementLeafDigest, + caDigest); + configureSeeder(fixture); + ReflectionTestUtils.invokeMethod(seeder, "loadFixtureCapability"); + // Disposable test schema only: create the real fixture owner from inception, never backfill. + flyway.clean(); + flyway.migrate(); + if (prepareExistingOwner) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + creationRepository.createCandidate( + NAMESPACE, operationId, "1", "Demo Game", "Seed game")); + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + seeder.run(new DefaultApplicationArguments(new String[] {})); + } + return fixture; + } + + protected void configureSeeder(Fixture fixture) { + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + ReflectionTestUtils.setField(seeder, "fixtureRunId", fixture.runId()); + ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", fixture.composeProjectName()); + ReflectionTestUtils.setField( + seeder, "fixtureCapabilityPath", fixture.capabilityPath().toString()); + ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); + ReflectionTestUtils.setField( + seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); + ReflectionTestUtils.setField( + seeder, "worldManagementLeafCertPath", fixture.worldManagementCertificatePath().toString()); + ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); + ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); + } + + protected String certificateDigest(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + } + + protected void awaitFixtureCertificatesValid(Path... certificatePaths) throws Exception { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (true) { + try { + for (Path path : certificatePaths) { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509").generateCertificate(input); + certificate.checkValidity(); + } + } + return; + } catch (CertificateNotYetValidException exception) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new IllegalStateException( + "Run-owned fixture certificates did not become valid within 5 seconds", exception); + } + TimeUnit.NANOSECONDS.sleep(Math.min(TimeUnit.MILLISECONDS.toNanos(10), remainingNanos)); + } + } + } + + protected AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { + String changedWorldSlug = source.worldSlug() + "-changed"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName()); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + changedWorldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + evidenceDigest); + } + + protected void runOpenSsl(String... arguments) throws Exception { + Process process = + new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) + .redirectErrorStream(true) + .start(); + String output = new String(process.getInputStream().readAllBytes()); + if (process.waitFor() != 0) { + throw new IOException("OpenSSL fixture certificate generation failed: " + output); + } + } + + protected String[] concat(String[] prefix, String[] suffix) { + String[] combined = new String[prefix.length + suffix.length]; + System.arraycopy(prefix, 0, combined, 0, prefix.length); + System.arraycopy(suffix, 0, combined, prefix.length, suffix.length); + return combined; + } + + protected record Fixture( + UUID operationId, + String runId, + String composeProjectName, + Path capabilityPath, + Path receiptPath, + Path gameSessionCertificatePath, + Path worldManagementCertificatePath, + Path caCertificatePath, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index c4c854fcae..a924b10f07 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -6,19 +6,21 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; -import java.io.IOException; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; -import java.security.MessageDigest; import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.Base64; -import java.util.HashSet; -import java.util.HexFormat; -import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -26,10 +28,16 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; import net.firedevops.firemud.gamedesign.data.TestDataSeeder; +import net.firedevops.firemud.gamedesign.data.TestDataSeederIntegrationSupport; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; @@ -44,28 +52,22 @@ import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; -import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; -import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; -import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.service.impl.GameDesignLaunchReadProjectionMapper; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; -import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record; import org.jooq.SQLDialect; -import org.jooq.Table; import org.jooq.impl.DSL; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.DefaultApplicationArguments; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; @@ -73,17 +75,11 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; 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.JsonNode; import tools.jackson.databind.ObjectMapper; @@ -93,6 +89,7 @@ classes = GameDesignServiceApplication.class, properties = { "spring.profiles.active=test", + "spring.config.import=file:src/main/resources/application.yml", "firemud.smoke.seed-demo-runtime.enabled=true", "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false", "spring.flyway.clean-disabled=false", @@ -107,58 +104,366 @@ "asset.store.secret-key=test-secret-key" }) @Import(NoGrpcServerTestConfiguration.class) -class TestDataSeederIntegrationTest { - private static final String NAMESPACE = "dev"; - private static final String SESSION_URI_SAN = "spiffe://firemud/ns/dev/sa/game-session-service"; - private static final String WORLD_MANAGEMENT_URI_SAN = - "spiffe://firemud/ns/dev/sa/world-management-service"; - private static final Table SOURCE_OPERATIONS = - DSL.table(DSL.name("game_design_authored_world_source_operations")); - private static final Table SOURCE_DELIVERIES = - DSL.table(DSL.name("game_design_authored_world_source_deliveries")); - private static final Field REGISTRATION_REQUEST_ID = - DSL.field(DSL.name("registration_request_id"), UUID.class); - private static final Field SOURCE_OPERATION_ID = - DSL.field(DSL.name("operation_id"), UUID.class); - private static final Field DELIVERY_WORLD_OPERATION_ID = - DSL.field(DSL.name("world_operation_id"), UUID.class); - - @Container - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @DynamicPropertySource - static void configure(DynamicPropertyRegistry registry) { - PostgresBackedServiceTestSupport.registerPostgresService( - registry, postgres, "game_design_service"); +class TestDataSeederIntegrationTest extends TestDataSeederIntegrationSupport { + @Test + void fixedWorldReadsQualifyRealPreexistingOwnersWithoutRewritingOrResolving( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); + seeder.run(new DefaultApplicationArguments(new String[] {})); + var capability = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseCapability(Files.readAllBytes(fixture.capabilityPath())); + var receipt = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(Files.readAllBytes(fixture.receiptPath()), capability); + var authorization = + new net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization( + fixtureReadback, + fixturePolicy, + NAMESPACE, + fixture.runId(), + fixture.composeProjectName(), + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.gameSessionCertificatePath().toString(), + fixture.worldManagementCertificatePath().toString(), + fixture.caCertificatePath().toString()); + var source = receipt.sourceEvidence(); + var sourceRequest = + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.toReadRequest( + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + source.worldSlug())); + var versionRequest = + net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(UUID.randomUUID().toString()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setWorldSlug(source.worldSlug()) + .setSourceOperationId(source.operationId().toString()) + .setExpectedSourceEvidenceDigest(source.evidenceDigest()) + .setVersionId(receipt.launchReadEvidence().versionState().getVersionId()) + .build(); + Map before = fixedReadOwnerRows(); + byte[] receiptBefore = Files.readAllBytes(fixture.receiptPath()); + X509Certificate actualMountedWorldLeaf; + try (var input = Files.newInputStream(fixture.worldManagementCertificatePath())) { + actualMountedWorldLeaf = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + // Peer context is controlled here; immutable PKI, producer and PostgreSQL owners are real. + var peerContext = + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri( + WORLD_MANAGEMENT_URI_SAN) + .orElseThrow()) + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence.fromCertificate( + actualMountedWorldLeaf) + .orElseThrow()); + org.mockito.Mockito.clearInvocations(launchDescriptorService); + peerContext.run( + () -> { + assertThat(authorization.authorizeSource(sourceRequest)).isEqualTo(receipt); + assertThat(authorization.authorizeVersion(versionRequest)).isEqualTo(receipt); + var sourceOutput = + new FixedReadObserver< + net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse>(); + new net.firedevops.firemud.gamedesign.service.impl + .RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, authoredWorldSourceRepository, NAMESPACE) + .resolveAuthoredWorldSource(sourceRequest, sourceOutput); + assertThat(sourceOutput.failure).isNull(); + assertThat(sourceOutput.completed).isTrue(); + assertThat( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec + .fromReadResponse( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec + .fromReadRequest(NAMESPACE, sourceRequest), + sourceOutput.value)) + .isEqualTo(source); + var versionOutput = + new FixedReadObserver< + net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse>(); + new net.firedevops.firemud.gamedesign.service.impl + .RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactionManager, authoredWorldSourceRepository, NAMESPACE) + .getAuthoredWorldVersionState(versionRequest, versionOutput); + assertThat(versionOutput.failure).isNull(); + assertThat(versionOutput.completed).isTrue(); + var actual = + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec + .fromResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec + .fromRequest(versionRequest), + versionOutput.value); + assertThat(actual.sourceEvidence()).isEqualTo(source); + assertThat(actual.versionStateEpoch()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionStateEpoch()); + }); + org.mockito.Mockito.verify(launchDescriptorService, org.mockito.Mockito.never()) + .resolveLaunchDescriptor(any()); + assertThat(fixedReadOwnerRows()).isEqualTo(before); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(receiptBefore); + org.mockito.Mockito.clearInvocations(authoredWorldSourceRepository, launchDescriptorService); + peerContext.run( + () -> { + assertThatThrownBy( + () -> + authorization.authorizeSource( + sourceRequest.toBuilder() + .setOperationId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeSource( + sourceRequest.toBuilder() + .setCanonicalTenantId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeSource( + sourceRequest.toBuilder().setWorldSlug("different-world").build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + versionRequest.toBuilder().setTargetNamespace("other").build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + versionRequest.toBuilder() + .setVersionId(versionRequest.getVersionId() + 1) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + versionRequest.toBuilder() + .setExpectedSourceEvidenceDigest("sha256:" + "f".repeat(64)) + .build())) + .isInstanceOf(SecurityException.class); + }); + org.mockito.Mockito.verifyNoInteractions( + authoredWorldSourceRepository, launchDescriptorService); + assertThat(fixedReadOwnerRows()).isEqualTo(before); } - @Autowired private TestDataSeeder seeder; - @Autowired private Flyway flyway; - @MockitoSpyBean private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; - @Autowired private GameRepository gameRepository; - - @Autowired - private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository - creationRepository; - - @Autowired private GameTemplateRepository templateRepository; - @Autowired private VersionRepository versionRepository; - @Autowired private VersionAssetArtifactRepository artifactRepository; - @Autowired private VersionService versionService; - @Autowired private VersionAssetArtifactService artifactService; - @Autowired private LaunchDescriptorRepository launchDescriptorRepository; - @MockitoSpyBean private LaunchDescriptorService launchDescriptorService; - @Autowired private PlatformTransactionManager transactionManager; - @Autowired private DSLContext dsl; - @Autowired private ObjectMapper objectMapper; - - @BeforeEach - void resetDisposableServiceSchema() { - ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); - flyway.clean(); - flyway.migrate(); + @Test + void fixedWorldClientsReadActualProducerOwnersOverMutualTlsWithoutOwnerWrites( + @TempDir Path testDirectory) throws Exception { + Fixture fixture = prepareFixture(testDirectory); + configureSeeder(fixture); seeder.run(new DefaultApplicationArguments(new String[] {})); + var capability = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseCapability(Files.readAllBytes(fixture.capabilityPath())); + var receipt = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(Files.readAllBytes(fixture.receiptPath()), capability); + var authorization = + new RunOwnedFixtureOwnerReadAuthorization( + fixtureReadback, + fixturePolicy, + NAMESPACE, + fixture.runId(), + fixture.composeProjectName(), + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + fixture.gameSessionCertificatePath().toString(), + fixture.worldManagementCertificatePath().toString(), + fixture.caCertificatePath().toString()); + var source = receipt.sourceEvidence(); + var sourceRequest = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + source.worldSlug()); + var versionRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + receipt.launchReadEvidence().versionState().getVersionId()); + var serverLeaf = + issueFixedReadLeaf( + fixture, "game-design-server", "spiffe://firemud/ns/dev/sa/game-design-service", true); + var otherWorldLeaf = + issueFixedReadLeaf(fixture, "different-world-client", WORLD_MANAGEMENT_URI_SAN, false); + var auth = + new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), + Set.of( + AuthoredWorldSourceReadServiceGrpc.getResolveAuthoredWorldSourceMethod() + .getFullMethodName(), + AuthoredWorldVersionStateServiceGrpc.getGetAuthoredWorldVersionStateMethod() + .getFullMethodName())); + Map originalRows = fixedReadOwnerRows(); + byte[] originalReceipt = Files.readAllBytes(fixture.receiptPath()); + // Actual handlers/interceptors on a loopback socket; Spring registration and Compose are + // separate proofs. + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverLeaf.certificate().toFile(), serverLeaf.privateKey().toFile())) + .trustManager(fixture.caCertificatePath().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, authoredWorldSourceRepository, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + auth)) + .addService( + ServerInterceptors.intercept( + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, + transactionManager, + authoredWorldSourceRepository, + NAMESPACE), + new GrpcPeerIdentityInterceptor(), + auth)) + .build() + .start(); + try { + org.mockito.Mockito.clearInvocations(launchDescriptorService, fixturePolicy); + withFixedReadClients( + server, + fixture, + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key"), + (sourceClient, versionClient) -> { + assertThat(sourceClient.read(sourceRequest)).isEqualTo(source); + var actual = versionClient.read(versionRequest); + assertThat(actual.request()).isEqualTo(versionRequest); + assertThat(actual.sourceEvidence()).isEqualTo(source); + assertThat(actual.canonicalVersionId()) + .isEqualTo( + UUID.fromString( + receipt + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId())); + assertThat(actual.versionState()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionState()); + assertThat(actual.versionStateEpoch()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionStateEpoch()); + }); + org.mockito.Mockito.verify(launchDescriptorService, org.mockito.Mockito.never()) + .resolveLaunchDescriptor(any()); + assertThat(org.mockito.Mockito.mockingDetails(fixturePolicy).getInvocations()) + .extracting(invocation -> invocation.getMethod().getName()) + .contains("readExisting") + .doesNotContain("sealAndRead"); + assertThat(fixedReadOwnerRows()).isEqualTo(originalRows); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); + org.mockito.Mockito.clearInvocations( + authoredWorldSourceRepository, launchDescriptorService, fixtureReadback, fixturePolicy); + for (var leaf : + java.util.List.of( + otherWorldLeaf, + new FixedReadLeaf( + fixture.gameSessionCertificatePath(), + fixture.gameSessionCertificatePath().resolveSibling("game-session.key")))) { + withFixedReadClients( + server, + fixture, + leaf.certificate(), + leaf.privateKey(), + (sourceClient, versionClient) -> { + assertSocketReadDenied(() -> sourceClient.read(sourceRequest)); + assertSocketReadDenied(() -> versionClient.read(versionRequest)); + }); + } + withFixedReadClients( + server, + fixture, + fixture.worldManagementCertificatePath(), + fixture.worldManagementCertificatePath().resolveSibling("world-management.key"), + (sourceClient, versionClient) -> { + assertSocketReadDenied( + () -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug()))); + assertSocketReadDenied( + () -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + UUID.randomUUID(), + source.worldSlug()))); + assertSocketReadDenied( + () -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + "different-world"))); + assertSocketReadDenied( + () -> + versionClient.read( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionRequest.versionId() + 1))); + assertSocketReadDenied( + () -> + versionClient.read( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + "sha256:" + "f".repeat(64), + versionRequest.versionId()))); + }); + org.mockito.Mockito.verifyNoInteractions( + authoredWorldSourceRepository, launchDescriptorService, fixtureReadback, fixturePolicy); + assertThat(fixedReadOwnerRows()).isEqualTo(originalRows); + assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(originalReceipt); + // No physical missing-header case: immutable producer seal precedes receipt publication. + // Controlled missing-policy denial is covered separately without forging/deleting owner + // evidence. + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } } @Test @@ -796,384 +1101,6 @@ void preservesConflictingReceiptInsteadOfReplacingIt(@TempDir Path testDirectory .isOne(); } - private Set fieldNames(JsonNode object) { - Set fields = new HashSet<>(); - object.propertyNames().forEach(fields::add); - return fields; - } - - private byte[] readPublishedReleaseBundleBytes() { - Record row = - dsl.fetchOne( - "select convert_to(row_to_json(release_bundle)::text, 'UTF8') as bundle_bytes " - + "from published_release_bundle as release_bundle " - + "where tenant_id = ? and version_id = ?", - "1", - 1L); - assertThat(row).isNotNull(); - return row.get("bundle_bytes", byte[].class); - } - - private void writeVersionStateEpoch( - TransactionTemplate transaction, String tenantId, Long versionId, long epoch) { - transaction.executeWithoutResult( - status -> { - int updated = - dsl.execute( - "update version set version_state_epoch = ? where tenant_id = ? and id = ?", - epoch, - tenantId, - versionId); - assertThat(updated).isOne(); - }); - } - - private Fixture prepareFixture(Path testDirectory) throws Exception { - return prepareFixture(testDirectory, true); - } - - private Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwner) - throws Exception { - Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); - Path caKey = certificateDirectory.resolve("ca.key"); - Path caCertificate = certificateDirectory.resolve("ca.crt"); - Path sessionKey = certificateDirectory.resolve("game-session.key"); - Path sessionRequest = certificateDirectory.resolve("game-session.csr"); - Path sessionCertificate = certificateDirectory.resolve("game-session.crt"); - Path sessionExtensions = certificateDirectory.resolve("game-session.ext"); - Path worldManagementKey = certificateDirectory.resolve("world-management.key"); - Path worldManagementRequest = certificateDirectory.resolve("world-management.csr"); - Path worldManagementCertificate = certificateDirectory.resolve("world-management.crt"); - Path worldManagementExtensions = certificateDirectory.resolve("world-management.ext"); - runOpenSsl( - "req", - "-x509", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-days", - "2", - "-keyout", - caKey.toString(), - "-out", - caCertificate.toString(), - "-subj", - "/CN=FireMUD test fixture CA", - "-addext", - "basicConstraints=critical,CA:TRUE", - "-addext", - "keyUsage=critical,keyCertSign,cRLSign"); - runOpenSsl( - "req", - "-new", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-keyout", - sessionKey.toString(), - "-out", - sessionRequest.toString(), - "-subj", - "/CN=game-session-service"); - Files.writeString( - sessionExtensions, - "basicConstraints=critical,CA:FALSE\n" - + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=clientAuth\n" - + "subjectAltName=URI:" - + SESSION_URI_SAN - + ",DNS:game-session-service" - + ",DNS:game-session-service.dev" - + ",DNS:game-session-service.dev.svc" - + ",DNS:game-session-service.dev.svc.cluster.local" - + "\n"); - runOpenSsl( - "x509", - "-req", - "-in", - sessionRequest.toString(), - "-CA", - caCertificate.toString(), - "-CAkey", - caKey.toString(), - "-CAcreateserial", - "-out", - sessionCertificate.toString(), - "-days", - "2", - "-sha256", - "-extfile", - sessionExtensions.toString()); - runOpenSsl( - "req", - "-new", - "-newkey", - "rsa:2048", - "-nodes", - "-sha256", - "-keyout", - worldManagementKey.toString(), - "-out", - worldManagementRequest.toString(), - "-subj", - "/CN=world-management-service"); - Files.writeString( - worldManagementExtensions, - "basicConstraints=critical,CA:FALSE\n" - + "keyUsage=critical,digitalSignature,keyEncipherment\n" - + "extendedKeyUsage=clientAuth\n" - + "subjectAltName=URI:" - + WORLD_MANAGEMENT_URI_SAN - + ",DNS:world-management-service" - + ",DNS:world-management-service.dev" - + ",DNS:world-management-service.dev.svc" - + ",DNS:world-management-service.dev.svc.cluster.local" - + "\n"); - runOpenSsl( - "x509", - "-req", - "-in", - worldManagementRequest.toString(), - "-CA", - caCertificate.toString(), - "-CAkey", - caKey.toString(), - "-CAcreateserial", - "-out", - worldManagementCertificate.toString(), - "-days", - "2", - "-sha256", - "-extfile", - worldManagementExtensions.toString()); - Files.setPosixFilePermissions( - caCertificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - Files.setPosixFilePermissions( - sessionCertificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - Files.setPosixFilePermissions( - worldManagementCertificate, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - - String leafDigest = certificateDigest(sessionCertificate); - String worldManagementLeafDigest = certificateDigest(worldManagementCertificate); - String caDigest = certificateDigest(caCertificate); - String runId = "fixture-commit-proof"; - String composeProjectName = "firemud-smoke-fixture-commit-proof"; - String claimDigest = "e".repeat(64); - UUID operationId = - net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec - .fixtureOperationId(claimDigest, runId, composeProjectName, leafDigest, caDigest); - Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); - Map capability = new LinkedHashMap<>(); - capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); - capability.put("runId", runId); - capability.put("composeProjectName", composeProjectName); - capability.put("claimDigest", claimDigest); - capability.put("operationId", operationId.toString()); - capability.put("tenantId", 1); - capability.put( - "gameTemplateId", - templateRepository.findByTenantIdAndName("1", "Default Template").orElseThrow().getId()); - capability.put("ownerAccountId", 1); - capability.put("worldSlug", "demo"); - capability.put("worldDisplayName", "Demo World"); - capability.put("realmSlug", "production"); - capability.put("realmDisplayName", "Live Realm"); - capability.put("visible", true); - capability.put("publicProductionRealm", true); - capability.put("requiresCharacterSelection", false); - capability.put("stateScope", "SHARED"); - capability.put("characterCreationPolicy", "ALLOW_NEW"); - capability.put("gameSessionLeafSha256", leafDigest); - capability.put("gameSessionUriSan", SESSION_URI_SAN); - capability.put("worldManagementLeafSha256", worldManagementLeafDigest); - capability.put("worldManagementUriSan", WORLD_MANAGEMENT_URI_SAN); - capability.put("caCertificateSha256", caDigest); - Files.write(capabilityPath, objectMapper.writeValueAsBytes(capability)); - Files.setPosixFilePermissions( - capabilityPath, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ)); - - awaitFixtureCertificatesValid(sessionCertificate, worldManagementCertificate, caCertificate); - - Path receiptDirectory = - Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); - Files.setPosixFilePermissions( - receiptDirectory, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE, - PosixFilePermission.GROUP_READ, - PosixFilePermission.GROUP_WRITE, - PosixFilePermission.GROUP_EXECUTE, - PosixFilePermission.OTHERS_READ, - PosixFilePermission.OTHERS_WRITE, - PosixFilePermission.OTHERS_EXECUTE)); - Fixture fixture = - new Fixture( - operationId, - runId, - composeProjectName, - capabilityPath, - receiptDirectory.resolve("source-receipt.json"), - sessionCertificate, - worldManagementCertificate, - caCertificate, - leafDigest, - worldManagementLeafDigest, - caDigest); - configureSeeder(fixture); - ReflectionTestUtils.invokeMethod(seeder, "loadFixtureCapability"); - // Disposable test schema only: create the real fixture owner from inception, never backfill. - flyway.clean(); - flyway.migrate(); - if (prepareExistingOwner) { - new TransactionTemplate(transactionManager) - .executeWithoutResult( - status -> - creationRepository.createCandidate( - NAMESPACE, operationId, "1", "Demo Game", "Seed game")); - ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); - seeder.run(new DefaultApplicationArguments(new String[] {})); - } - return fixture; - } - - private void configureSeeder(Fixture fixture) { - ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); - ReflectionTestUtils.setField(seeder, "fixtureRunId", fixture.runId()); - ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", fixture.composeProjectName()); - ReflectionTestUtils.setField( - seeder, "fixtureCapabilityPath", fixture.capabilityPath().toString()); - ReflectionTestUtils.setField(seeder, "fixtureReceiptPath", fixture.receiptPath().toString()); - ReflectionTestUtils.setField( - seeder, "gameSessionLeafCertPath", fixture.gameSessionCertificatePath().toString()); - ReflectionTestUtils.setField( - seeder, "worldManagementLeafCertPath", fixture.worldManagementCertificatePath().toString()); - ReflectionTestUtils.setField(seeder, "workloadNamespace", NAMESPACE); - ReflectionTestUtils.setField(seeder, "caCertPath", fixture.caCertificatePath().toString()); - } - - private String certificateDigest(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - X509Certificate certificate = - (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); - } - } - - private void awaitFixtureCertificatesValid(Path... certificatePaths) throws Exception { - long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (true) { - try { - for (Path path : certificatePaths) { - try (var input = Files.newInputStream(path)) { - X509Certificate certificate = - (X509Certificate) - CertificateFactory.getInstance("X.509").generateCertificate(input); - certificate.checkValidity(); - } - } - return; - } catch (CertificateNotYetValidException exception) { - long remainingNanos = deadlineNanos - System.nanoTime(); - if (remainingNanos <= 0L) { - throw new IllegalStateException( - "Run-owned fixture certificates did not become valid within 5 seconds", exception); - } - TimeUnit.NANOSECONDS.sleep(Math.min(TimeUnit.MILLISECONDS.toNanos(10), remainingNanos)); - } - } - } - - private AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { - String changedWorldSlug = source.worldSlug() + "-changed"; - String requestDigest = - AuthoredWorldSourceDigest.requestDigest( - source.targetNamespace(), - source.registrationRequestId(), - source.canonicalTenantId(), - source.tenantSlug(), - changedWorldSlug, - source.worldDisplayName()); - String evidenceDigest = - AuthoredWorldSourceDigest.evidenceDigest( - source.targetNamespace(), - source.registrationRequestId(), - source.operationId(), - requestDigest, - source.canonicalTenantId(), - source.tenantSlug(), - changedWorldSlug, - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind()); - return new AuthoredWorldSourceEvidence( - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.operationId(), - requestDigest, - source.canonicalTenantId(), - source.tenantSlug(), - changedWorldSlug, - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - evidenceDigest); - } - - private void runOpenSsl(String... arguments) throws Exception { - Process process = - new ProcessBuilder(concat(new String[] {"openssl"}, arguments)) - .redirectErrorStream(true) - .start(); - String output = new String(process.getInputStream().readAllBytes()); - if (process.waitFor() != 0) { - throw new IOException("OpenSSL fixture certificate generation failed: " + output); - } - } - - private String[] concat(String[] prefix, String[] suffix) { - String[] combined = new String[prefix.length + suffix.length]; - System.arraycopy(prefix, 0, combined, 0, prefix.length); - System.arraycopy(suffix, 0, combined, prefix.length, suffix.length); - return combined; - } - - private record Fixture( - UUID operationId, - String runId, - String composeProjectName, - Path capabilityPath, - Path receiptPath, - Path gameSessionCertificatePath, - Path worldManagementCertificatePath, - Path caCertificatePath, - String gameSessionLeafSha256, - String worldManagementLeafSha256, - String caCertificateSha256) {} - @Test void freshBaselineSeedAndRestartReuseActualOwnerIdentityAndOpaqueBundle() { FoundationFixture fixture = foundationFixture(null); @@ -1475,7 +1402,9 @@ void migrate(String target) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); if (target != null) configuration.target(target); configuration.load().migrate(); } @@ -1529,4 +1458,27 @@ String artifactXmin() { .get("xmin", String.class); } } + + private static final class FixedReadObserver implements io.grpc.stub.StreamObserver { + public FixedReadObserver() {} + + public T value; + public Status.Code failure; + public boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable error) { + failure = Status.fromThrowable(error).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index b6090e4809..d8d340f0ff 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -962,7 +962,11 @@ private static Fixture fixture(boolean branding) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .table("flyway_schema_history_game_design_service") .load() .migrate(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index 7d9706c214..77b644edbc 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -1032,7 +1032,7 @@ private static Fixture freshFixture() { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations(migrationLocation()) .table("flyway_schema_history_game_design_service") .load() .migrate(); @@ -1206,7 +1206,7 @@ private static void migrate(DriverManagerDataSource dataSource, String schema, S .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations(migrationLocation()) .table("flyway_schema_history_game_design_service") .target(target) .load() @@ -1262,4 +1262,9 @@ T tx(Supplier work) { return write.execute(status -> work.get()); } } + + private static String migrationLocation() { + return "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index e3f73cbc8f..c8f2599079 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -46,7 +46,6 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -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; @@ -168,16 +167,21 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageTail( @TempDir Path parentMigrations) throws Exception { var fixture = fixture(true); - var resources = - new PathMatchingResourcePatternResolver().getResources("classpath*:db/migration/**/*.sql"); int copied = 0; - for (var resource : resources) { - 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)); + for (Path directory : + List.of( + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize())) { + try (var migrations = Files.list(directory)) { + for (Path migration : migrations.filter(Files::isRegularFile).sorted().toList()) { + String filename = java.util.Objects.requireNonNull(migration.getFileName()).toString(); + if (!PARENT_MIGRATION_SCRIPTS.contains(filename)) continue; + Files.copy(migration, parentMigrations.resolve(filename)); + copied++; + } } - copied++; } assertThat(copied).isEqualTo(62); flyway(fixture.source(), fixture.schema(), null, "filesystem:" + parentMigrations).migrate(); @@ -944,7 +948,15 @@ private String reviewedBaseRow(Fixture fixture, DraftCommitBinding binding) { } private Flyway flyway(DriverManagerDataSource source, String schema, String target) { - return flyway(source, schema, target, "classpath:db/migration", "classpath:db/migration/saga"); + return flyway( + source, + schema, + target, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()); } private Flyway flyway( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index e5f6313bcb..cf5dcca579 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -1433,7 +1433,9 @@ private Fixture fixture( .schemas(schema) .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .table("flyway_schema_history_game_design_service"); if (migrationTarget != null) { flyway.target(migrationTarget); @@ -1579,7 +1581,9 @@ private Fixture fixture( .schemas(schema) .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) .table("flyway_schema_history_game_design_service") .load() .migrate()); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 22e514dc6b..6a6ddd9a12 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -550,7 +550,11 @@ private static void migrate( .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .table("flyway_schema_history_game_design_service"); if (migrationTarget != null) configuration.target(migrationTarget); configuration.load().migrate(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java index 761f4b42df..8e9a89e7b9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -545,7 +545,11 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio .defaultSchema(schema) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java index ae59cafd2b..086d6446cc 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -109,7 +109,11 @@ private Fixture fixture() { .defaultSchema(schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .load() .migrate(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java index 278907d248..20f4480856 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java @@ -207,7 +207,11 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio .defaultSchema(schema) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java index 7bf87d3332..437019f04c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java @@ -601,7 +601,11 @@ private Fixture fixture(MigrationVersion target, byte[] sourceBytes) { .defaultSchema(schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } @@ -793,7 +797,11 @@ private static void migrateToLatest(Fixture fixture) { .defaultSchema(fixture.schema) .table("flyway_schema_history_game_design_service") .placeholders(Map.of("serviceSchema", fixture.schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .load() .migrate(); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 8a8b966cab..2649cdb0e7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.file.Path; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Map; @@ -48,6 +49,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.core.JdbcTemplate; @@ -69,6 +71,7 @@ classes = GameDesignServiceApplication.class, properties = { "spring.profiles.active=test", + "spring.config.import=file:src/main/resources/application.yml", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", "firemud.grpc.workload-namespace=launch-descriptor-test", @@ -115,9 +118,46 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PlatformTransactionManager transactionManager; @Autowired private DSLContext dsl; @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private ConfigurableEnvironment environment; @Test - void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() { + void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() throws Exception { + assertThat(environment.getRequiredProperty("spring.application.name")) + .isEqualTo("game-design-service"); + var applicationNameOrigin = + environment.getPropertySources().stream() + .filter(source -> source.containsProperty("spring.application.name")) + .map( + source -> + org.springframework.boot.origin.OriginLookup.getOrigin( + source, "spring.application.name")) + .filter(java.util.Objects::nonNull) + .findFirst() + .orElseThrow( + () -> new AssertionError("spring.application.name has no config data origin")); + while (applicationNameOrigin + instanceof org.springframework.boot.origin.PropertySourceOrigin wrapper) { + applicationNameOrigin = + java.util.Objects.requireNonNull( + wrapper.getOrigin(), "spring.application.name origin wrapper has no concrete parent"); + } + assertThat(applicationNameOrigin) + .as("origin for spring.application.name: %s", applicationNameOrigin) + .isInstanceOf(org.springframework.boot.origin.TextResourceOrigin.class); + Path actualApplicationConfig = + java.util.Objects.requireNonNull( + ((org.springframework.boot.origin.TextResourceOrigin) applicationNameOrigin) + .getResource()) + .getFile() + .toPath() + .toRealPath(); + Path expectedApplicationConfig = Path.of("src/main/resources/application.yml").toRealPath(); + assertThat(actualApplicationConfig) + .withFailMessage( + "spring.application.name came from %s, expected GDS config %s", + actualApplicationConfig, expectedApplicationConfig) + .isEqualTo(expectedApplicationConfig); + assertThatThrownBy( () -> legacyLaunchDescriptorService.resolveLaunchDescriptor( @@ -1000,7 +1040,11 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio .defaultSchema(schema) .table(FLYWAY_TABLE) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); if (target != null) { configuration.target(target); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java index 546d3fc31e..2486a381ff 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -97,6 +97,8 @@ private static void assertConfiguredGrpcMethods(String fileName) throws IOExcept .getFullMethodName(), "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor", "gamedesign.v1.GameDesignService/GetLaunchDescriptor", - "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding")); + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding", + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState")); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java new file mode 100644 index 0000000000..e1de4bc5c7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamedesign.data; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.junit.jupiter.api.Test; + +/** Controlled configuration/peer doubles; committed producer/storage proof is native. */ +class RunOwnedFixtureOwnerReadAuthorizationTest { + @Test + void missingFixedConfigurationFailsClosedWithoutOwnerAccess() { + var readback = mock(RunOwnedFixtureLaunchReadback.class); + var policy = mock(RunOwnedFixturePolicyProducer.class); + assertThatThrownBy( + () -> + new RunOwnedFixtureOwnerReadAuthorization( + readback, policy, "dev", "", "", "", "", "", "", "")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(readback, policy); + } + + @Test + void callerMissingPeerWrongNamespaceServiceAndLeafDenyBeforeMalformedSelector() throws Exception { + var readback = mock(RunOwnedFixtureLaunchReadback.class); + var policy = mock(RunOwnedFixturePolicyProducer.class); + var trusted = mock(TestDataSeeder.FixtureCapability.class); + when(trusted.worldManagementLeafSha256()).thenReturn("a".repeat(64)); + try (var configuration = mockStatic(TestDataSeeder.class)) { + configuration + .when( + () -> + TestDataSeeder.verifyFixtureConfiguration( + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString())) + .thenReturn(trusted); + var authorization = + new RunOwnedFixtureOwnerReadAuthorization( + readback, + policy, + "dev", + "controlled-run", + "controlled-project", + "/controlled-capability", + "/controlled-receipt", + "/controlled-gs", + "/controlled-world", + "/controlled-ca"); + assertBothDeny(authorization); + SessionContext.setContext("controlled-account", List.of("player"), Map.of()); + try { + assertBothDeny(authorization); + } finally { + SessionContext.clear(); + } + X509Certificate controlledLeaf = mock(X509Certificate.class); + when(controlledLeaf.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + var certificate = GrpcPeerCertificateEvidence.fromCertificate(controlledLeaf).orElseThrow(); + for (String uri : + List.of( + "spiffe://firemud/ns/dev/sa/game-session-service", + "spiffe://firemud/ns/other/sa/world-management-service", + "spiffe://firemud/ns/dev/sa/world-management-service")) { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate) + .run(() -> assertBothDeny(authorization)); + } + verifyNoInteractions(readback, policy); + } + } + + @Test + void rawReceiptAndQualifiedLaunchStillRequirePreexistingPolicyWithoutSealing() throws Exception { + var readback = mock(RunOwnedFixtureLaunchReadback.class); + var policy = mock(RunOwnedFixturePolicyProducer.class); + var trusted = mock(TestDataSeeder.FixtureCapability.class); + var capability = + mock( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.Capability + .class); + var receipt = + mock( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .SourceReceipt.class); + var source = mock(net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence.class); + var operation = java.util.UUID.randomUUID(); + var canonical = java.util.UUID.randomUUID(); + when(source.targetNamespace()).thenReturn("dev"); + when(source.operationId()).thenReturn(operation); + when(source.canonicalTenantId()).thenReturn(canonical); + when(source.worldSlug()).thenReturn("fixture-world"); + when(receipt.sourceEvidence()).thenReturn(source); + var creation = mock(net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence.class); + when(receipt.creationEvidence()).thenReturn(creation); + when(trusted.wire()).thenReturn(capability); + var committed = + new RunOwnedFixtureLaunchReadback.CommittedReceipt( + mock(RunOwnedFixtureLaunchReadback.Snapshot.class), + mock(net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto.class)); + when(readback.readCommittedReceipt(receipt)).thenReturn(committed); + when(policy.readExisting(trusted, creation, committed.snapshot(), committed.descriptor())) + .thenThrow(new IllegalStateException("Preexisting sealed fixture policy unavailable")); + X509Certificate controlledLeaf = mock(X509Certificate.class); + when(controlledLeaf.getEncoded()).thenReturn(new byte[] {4, 5, 6}); + var certificate = GrpcPeerCertificateEvidence.fromCertificate(controlledLeaf).orElseThrow(); + when(trusted.worldManagementLeafSha256()).thenReturn(certificate.leafSha256()); + try (var configuration = mockStatic(TestDataSeeder.class); + var files = + mockStatic( + net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader.class); + var wire = + mockStatic( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .class)) { + configuration + .when( + () -> + TestDataSeeder.verifyFixtureConfiguration( + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString())) + .thenReturn(trusted); + byte[] controlledReceipt = new byte[] {7}; + files + .when( + () -> + net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader + .readBoundedImmutableFile(any(java.nio.file.Path.class), anyInt(), any())) + .thenReturn(controlledReceipt); + wire.when( + () -> + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(controlledReceipt, capability)) + .thenReturn(receipt); + var authorization = + new RunOwnedFixtureOwnerReadAuthorization( + readback, + policy, + "dev", + "controlled-run", + "controlled-project", + "/controlled-capability", + "/controlled-receipt", + "/controlled-gs", + "/controlled-world", + "/controlled-ca"); + var request = + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.toReadRequest( + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest( + "dev", java.util.UUID.randomUUID(), operation, canonical, "fixture-world")); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/dev/sa/world-management-service") + .orElseThrow()) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate) + .run( + () -> + assertThatThrownBy(() -> authorization.authorizeSource(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Preexisting")); + verify(readback).readCommittedReceipt(receipt); + verify(policy).readExisting(trusted, creation, committed.snapshot(), committed.descriptor()); + verify(policy, never()).sealAndRead(any(), any(), any(), any()); + } + } + + private static void assertBothDeny(RunOwnedFixtureOwnerReadAuthorization authorization) { + assertThatThrownBy( + () -> + authorization.authorizeSource( + ResolveAuthoredWorldSourceRequest.getDefaultInstance())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + authorization.authorizeVersion( + GetAuthoredWorldVersionStateRequest.getDefaultInstance())) + .isInstanceOf(SecurityException.class); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java index c422c55ff0..71e3c9938d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -66,7 +66,9 @@ class CanonicalLaunchGrpcAuthWiringTest { "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies", RESOLVE_LAUNCH_DESCRIPTOR_METHOD, GET_LAUNCH_DESCRIPTOR_METHOD, - GET_COMPLETE_LAUNCH_BINDING_METHOD); + GET_COMPLETE_LAUNCH_BINDING_METHOD, + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String WORLD_MANAGEMENT_URI = "spiffe://firemud/ns/test/sa/world-management-service"; @@ -263,6 +265,41 @@ void playerJwtCannotSubstituteForMissingGameSessionPeerIdentity() { assertAllLaunchHandlersDeny(interceptor(jwtUtil), null, playerJwt); } + @Test + void fixedOwnerReadBypassesAreExactInBothConfigurationProfiles() throws Exception { + for (String resource : List.of("application.yml", "application-prod.yml")) { + var factory = new org.springframework.beans.factory.config.YamlPropertiesFactoryBean(); + factory.setResources( + new org.springframework.core.io.FileSystemResource("src/main/resources/" + resource)); + var properties = java.util.Objects.requireNonNull(factory.getObject()); + var methods = + properties.stringPropertyNames().stream() + .filter(key -> key.startsWith("firemud.auth.grpc.public-methods[")) + .map(properties::getProperty) + .toList(); + assertThat(methods).containsExactlyInAnyOrderElementsOf(ALLOWLISTED_METHODS); + assertThat(methods) + .doesNotContain( + UNLISTED_METHOD, + "gamedesign.v1.GameDesignService/GetVersionState", + "gamedesign.v1.GameDesignService/GetVersionAssetArtifactState"); + } + for (String method : ALLOWLISTED_METHODS.subList(6, 8)) { + var result = + dispatch( + interceptor(), + null, + new Metadata(), + method, + GetPublishedReleaseBundleRequest.getDefaultInstance(), + GetPublishedReleaseBundleResponse.getDefaultInstance(), + GetPublishedReleaseBundleRequest.getDefaultInstance(), + (request, observer) -> observer.onCompleted()); + assertThat(result.dispatched()).isTrue(); + assertThat(result.closedStatus()).isNull(); + } + } + @Test void unlistedGameDesignMethodStillRequiresBearerToken() { AuthTokenInterceptor interceptor = interceptor(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index c76256c058..949b1dd1ff 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -72,7 +72,9 @@ class TenantIdentityGrpcAuthWiringTest { POLICY_LIST_METHOD, RESOLVE_LAUNCH_DESCRIPTOR_METHOD, GET_LAUNCH_DESCRIPTOR_METHOD, - GET_COMPLETE_LAUNCH_BINDING_METHOD); + GET_COMPLETE_LAUNCH_BINDING_METHOD, + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String SOURCE_KEY = "fresh-owner-key-91"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java index 0455f09e6f..fef128fe17 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -1,6 +1,7 @@ package unit.net.firedevops.firemud.gamedesign.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -180,7 +181,7 @@ void classifiesJooqStorageFailuresByConnectionSqlStateWithoutLeakingDetails() { } private static void assertStorageFailure(WorldSourceObserver observer, Status.Code expectedCode) { - assertThat(observer.failure).isEqualTo(expectedCode); + assertThat(observer.failure).as("owner storage code").isEqualTo(expectedCode); assertThat(observer.response).isNull(); assertThat(observer.completed).isFalse(); assertThat(observer.failureDescription) @@ -298,4 +299,32 @@ public void onCompleted() { completed = true; } } + + @Test + void storageFailureClassificationRetriesOnlyConnectionAndTimeoutTransactions() { + var failures = + new org.springframework.transaction.TransactionException[] { + new org.springframework.transaction.CannotCreateTransactionException( + "connection unavailable"), + new org.springframework.transaction.TransactionTimedOutException("timed out"), + new org.springframework.transaction.IllegalTransactionStateException( + "propagation mismatch"), + new org.springframework.transaction.UnexpectedRollbackException("rollback only"), + new org.springframework.transaction.NestedTransactionNotSupportedException( + "nested unsupported"), + new org.springframework.transaction.InvalidIsolationLevelException( + "isolation unsupported") + }; + for (int index = 0; index < failures.length; index++) { + var failure = failures[index]; + doThrow(failure) + .when(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test"); + var observer = callWorldSource(worldSourceRequest(), WORLD_URI); + assertThat(observer.failure) + .as("transaction %s", failure.getClass().getSimpleName()) + .isEqualTo(index < 2 ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL); + assertStorageFailure(observer, index < 2 ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL); + } + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java index 003f4ad7bf..c353a60676 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -196,6 +196,34 @@ void classifiesSpringAndJooqStorageFailuresWithoutLeakingDetails() { assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); } + @Test + void retriesOnlyConnectionAndTimeoutTransactions() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + when(service.read(request())) + .thenThrow( + new org.springframework.transaction.CannotCreateTransactionException( + "connection unavailable")) + .thenThrow(new org.springframework.transaction.TransactionTimedOutException("timed out")) + .thenThrow( + new org.springframework.transaction.IllegalTransactionStateException( + "propagation mismatch")) + .thenThrow(new org.springframework.transaction.UnexpectedRollbackException("rollback only")) + .thenThrow( + new org.springframework.transaction.NestedTransactionNotSupportedException( + "nested unsupported")) + .thenThrow( + new org.springframework.transaction.InvalidIsolationLevelException( + "isolation unsupported")); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + + assertTransactionFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertTransactionFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertTransactionFailure(callRead(handler), Status.Code.INTERNAL); + assertTransactionFailure(callRead(handler), Status.Code.INTERNAL); + assertTransactionFailure(callRead(handler), Status.Code.INTERNAL); + assertTransactionFailure(callRead(handler), Status.Code.INTERNAL); + } + private static TestObserver callRead( AuthoredWorldVersionStateGrpcService handler) { TestObserver observer = new TestObserver<>(); @@ -207,6 +235,18 @@ private static TestObserver callRead( return observer; } + private static void assertTransactionFailure(TestObserver observer, Status.Code expectedCode) { + assertStatus(observer, expectedCode); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(observer.failureDescription) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "Game Design owner snapshot is temporarily unavailable" + : "Game Design owner snapshot could not be read"); + assertThat(observer.failureTrailersPresent).isFalse(); + } + private static void assertStorageFailure(TestObserver observer, Status.Code expectedCode) { assertStatus(observer, expectedCode); assertThat(observer.value).isNull(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java new file mode 100644 index 0000000000..42f442ee2e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java @@ -0,0 +1,303 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; +import net.firedevops.firemud.gamedesign.data.RunOwnedFixtureOwnerReadAuthorization; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.RunOwnedFixtureAuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.TransientDataAccessResourceException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest { + @Test + void fixedServicesRemainUnregisteredByDefaultAndUseExistingServiceIdsWhenEnabled() { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + // This registration test uses a controlled authorization bean, not producer authority. + var runner = + new ApplicationContextRunner() + .withBean(RunOwnedFixtureOwnerReadAuthorization.class, () -> authorization) + .withBean(GameAuthoredWorldSourceRepository.class, () -> repository) + .withBean(PlatformTransactionManager.class, () -> transactions) + .withUserConfiguration( + RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class, + RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + runner.run( + context -> { + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + }); + runner + .withPropertyValues("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false") + .run( + context -> { + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + }); + runner + .withPropertyValues( + "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true", + "firemud.grpc.workload-namespace=dev") + .run( + context -> { + assertThat( + context + .getBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class) + .bindService() + .getServiceDescriptor() + .getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); + assertThat( + context + .getBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class) + .bindService() + .getServiceDescriptor() + .getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); + }); + verifyNoInteractions(repository, transactions, authorization); + } + + @Test + void authorizationDenialAndMissingPreexistingOwnerNeverReachKernelsOrPublishResponses() { + for (RuntimeException refusal : + new RuntimeException[] { + new SecurityException("controlled peer refusal"), + new IllegalStateException("preexisting policy owner missing") + }) { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(authorization.authorizeSource(any())).thenThrow(refusal); + when(authorization.authorizeVersion(any())).thenThrow(refusal); + var sourceFailure = new AtomicReference(); + var versionFailure = new AtomicReference(); + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService(authorization, repository, "dev") + .resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest.getDefaultInstance(), + refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest.getDefaultInstance(), + refusingObserver(versionFailure)); + var expected = + refusal instanceof SecurityException + ? Status.Code.PERMISSION_DENIED + : Status.Code.FAILED_PRECONDITION; + assertThat(Status.fromThrowable(sourceFailure.get()).getCode()).isEqualTo(expected); + assertThat(Status.fromThrowable(versionFailure.get()).getCode()).isEqualTo(expected); + verifyNoInteractions(repository, transactions); + } + } + + @Test + void fixtureReadFailuresKeepRequestAuthorityAndStorageStatusesDistinct() { + for (var failure : failureCases()) { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(authorization.authorizeSource(any())).thenThrow(failure.exception()); + when(authorization.authorizeVersion(any())).thenThrow(failure.exception()); + var sourceFailure = new AtomicReference(); + var versionFailure = new AtomicReference(); + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService(authorization, repository, "dev") + .resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest.getDefaultInstance(), + refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest.getDefaultInstance(), + refusingObserver(versionFailure)); + assertThat(Status.fromThrowable(sourceFailure.get()).getCode()) + .as("source transaction/storage %s", failure.exception().getClass().getSimpleName()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(versionFailure.get()).getCode()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(sourceFailure.get()).getDescription()) + .doesNotContain("connection lost", "duplicate key", "storage unavailable"); + if (failure.expectedCode() == Status.Code.UNAVAILABLE + || failure.expectedCode() == Status.Code.INTERNAL) { + assertThat(Status.fromThrowable(versionFailure.get()).getDescription()) + .isEqualTo( + failure.expectedCode() == Status.Code.UNAVAILABLE + ? "Game Design Version state is temporarily unavailable" + : "Game Design Version state could not be read"); + } + verifyNoInteractions(repository, transactions); + } + } + + @Test + void authorizedStorageFailuresReachRepositoriesAndTransactions() { + var sourceRequest = + ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId("11111111-1111-4111-8111-111111111111") + .setOperationId("22222222-2222-4222-8222-222222222222") + .setCanonicalTenantId("33333333-3333-4333-8333-333333333333") + .setWorldSlug("demo-world") + .build(); + var versionRequest = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("dev") + .setReadRequestId(sourceRequest.getRequestId()) + .setSourceOperationId(sourceRequest.getOperationId()) + .setCanonicalTenantId(sourceRequest.getCanonicalTenantId()) + .setWorldSlug(sourceRequest.getWorldSlug()) + .setExpectedSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .setVersionId(1) + .build(); + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/dev/sa/world-management-service") + .orElseThrow()); + for (var failure : failureCases()) { + if (failure.expectedCode() != Status.Code.UNAVAILABLE + && failure.expectedCode() != Status.Code.INTERNAL) continue; + for (boolean transactionFailure : new boolean[] {false, true}) { + var authorization = mock(RunOwnedFixtureOwnerReadAuthorization.class); + var repository = mock(GameAuthoredWorldSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var receipt = mock(SourceReceipt.class); + when(authorization.authorizeSource(sourceRequest)).thenReturn(receipt); + when(authorization.authorizeVersion(versionRequest)).thenReturn(receipt); + when(repository.read(any(), any(), any(), any())).thenThrow(failure.exception()); + if (transactionFailure) { + when(transactions.getTransaction(any())).thenThrow(failure.exception()); + } else { + when(transactions.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(repository.readVersionStateSnapshot( + any(), any(), any(), any(), any(), any(), org.mockito.ArgumentMatchers.anyLong())) + .thenThrow(failure.exception()); + } + var sourceFailure = new AtomicReference(); + var versionFailure = new AtomicReference(); + peer.run( + () -> { + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, repository, "dev") + .resolveAuthoredWorldSource(sourceRequest, refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState(versionRequest, refusingObserver(versionFailure)); + }); + assertThat(Status.fromThrowable(sourceFailure.get()).getCode()) + .as("authorized source storage %s", failure.exception().getClass().getSimpleName()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(versionFailure.get()).getCode()) + .as( + "authorized Version %s failure %s", + transactionFailure ? "transaction" : "repository", + failure.exception().getClass().getSimpleName()) + .isEqualTo(failure.expectedCode()); + assertThat(Status.fromThrowable(sourceFailure.get()).getDescription()) + .doesNotContain(failure.exception().getMessage()); + assertThat(Status.fromThrowable(versionFailure.get()).getDescription()) + .doesNotContain(failure.exception().getMessage()); + verify(repository).read(any(), any(), any(), any()); + verify(transactions).getTransaction(any()); + if (!transactionFailure) + verify(repository) + .readVersionStateSnapshot( + any(), any(), any(), any(), any(), any(), org.mockito.ArgumentMatchers.anyLong()); + } + } + } + + private static FailureCase[] failureCases() { + return new FailureCase[] { + new FailureCase( + new SecurityException("controlled peer refusal"), Status.Code.PERMISSION_DENIED), + new FailureCase( + new IllegalArgumentException("owner selector mismatch"), Status.Code.FAILED_PRECONDITION), + new FailureCase( + new RunOwnedFixtureOwnerReadAuthorization.RequestDecodingException( + new IllegalArgumentException("malformed wire request")), + Status.Code.INVALID_ARGUMENT), + new FailureCase( + new DataAccessResourceFailureException("storage unavailable"), Status.Code.UNAVAILABLE), + new FailureCase( + new TransientDataAccessResourceException("transient storage failure"), + Status.Code.UNAVAILABLE), + new FailureCase( + new CannotCreateTransactionException("transaction unavailable"), Status.Code.UNAVAILABLE), + new FailureCase( + new org.springframework.transaction.TransactionTimedOutException("transaction timed out"), + Status.Code.UNAVAILABLE), + new FailureCase( + new org.springframework.transaction.IllegalTransactionStateException( + "propagation mismatch"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.UnexpectedRollbackException("rollback only"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.NestedTransactionNotSupportedException( + "nested unsupported"), + Status.Code.INTERNAL), + new FailureCase( + new org.springframework.transaction.InvalidIsolationLevelException( + "isolation unsupported"), + Status.Code.INTERNAL), + new FailureCase( + new DataIntegrityViolationException( + "connection failed", new SQLException("connection lost", "08006")), + Status.Code.UNAVAILABLE), + new FailureCase( + new DataIntegrityViolationException( + "constraint rejected", new SQLException("duplicate key", "23505")), + Status.Code.INTERNAL) + }; + } + + private record FailureCase(RuntimeException exception, Status.Code expectedCode) {} + + private static StreamObserver refusingObserver(AtomicReference failure) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + throw new AssertionError("Refused read emitted success"); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("Refused read completed"); + } + }; + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java index 1647d1925a..10f908bd74 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java @@ -496,6 +496,63 @@ private static void withPeer(GrpcPeerIdentity peer, Runnable action) { } } + @Test + void resolveLookRejectsInternalProbeBeforeAggregation() { + var attestations = + new GameplaySessionAttestationService( + new net.firedevops.firemud.common.security.JwtUtil( + "test-secret-123456789012345678901234567890", 3_600_000L)); + var look = Mockito.mock(LookAggregationService.class); + var dispatcher = new EventDispatcher(); + var commands = + new CommandServiceImpl( + new DefaultCommandParser(), + new SimpleCommandProcessor(dispatcher, new NoOpScriptingHook())); + var service = + new GameLogicGrpcService( + new PingServiceImpl(), + commands, + look, + Mockito.mock(CommunicationAggregationService.class), + Mockito.mock(MoveAggregationService.class), + Mockito.mock(ItemRuntimeService.class), + mockDigestService(), + attestations, + new SimpleMeterRegistry()); + var result = new AtomicReference(); + + service.resolveLook( + LookRequest.newBuilder() + .setTenantId("22") + .setSessionId("41") + .setCharacterId("123") + .setRoomInstance( + RoomInstanceRef.newBuilder() + .setTenantId("22") + .setGameInstanceId("1") + .setRoomInstanceId("R-1021")) + .setSessionAttestation(attestations.issueInternalProbeAttestation("22", "1", "R-1021")) + .build(), + new StreamObserver<>() { + @Override + public void onNext(LookResult value) { + result.set(value); + } + + @Override + public void onError(Throwable error) { + fail(error); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("SESSION_ATTESTATION_INVALID", result.get().getError().getCode()); + assertTrue(result.get().getError().getMessage().contains("type is unsupported")); + Mockito.verifyNoInteractions(look); + } + @Test void resolveLookReturnsErrorDetailInsteadOfTransportError() { PingService pingService = new PingServiceImpl(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index e192fad1db..a2720f8f0f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -124,27 +124,11 @@ public LookResult resolveLook(SessionContext context, String roomId, String loca return callStub().resolveLook(request); } - public LookResult resolveLookForReadiness( - String tenantId, String sessionId, String characterId, String gameInstanceId, String roomId) { - String canonicalRoomId = GameplayRuntimeRoomIds.requireCanonical(roomId, "roomInstanceId"); - LookRequest request = - LookRequest.newBuilder() - .setTenantId(tenantId) - .setSessionId(sessionId) - .setCharacterId(characterId) - .setRoomInstance( - RoomInstanceRef.newBuilder() - .setTenantId(tenantId) - .setGameInstanceId(gameInstanceId == null ? "" : gameInstanceId) - .setRoomInstanceId(canonicalRoomId) - .build()) - .setSessionAttestation( - gameplaySessionAttestationService.issueInternalProbeAttestation( - tenantId, gameInstanceId, canonicalRoomId)) - .build(); + /** Authenticated connectivity conjunct; downstream readiness is checked separately. */ + public PingResponse pingForReadiness() { return stub() .withDeadlineAfter(READINESS_DEADLINE_SECONDS, TimeUnit.SECONDS) - .resolveLook(request); + .ping(PingRequest.getDefaultInstance()); } public SendCommunicationResponse sendCommunication( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameLogicProperties.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameLogicProperties.java index 91ee2b6f5c..119b2e33c4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameLogicProperties.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameLogicProperties.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.config; +import java.net.URI; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -7,4 +8,28 @@ @ConfigurationProperties(prefix = "game.logic") public class GameLogicProperties { private String defaultRoomId = "R-1021"; + private String readinessUrl = ""; + + /** Only the configured internal actuator readiness endpoint may be probed. */ + public URI readinessEndpoint() { + if (readinessUrl == null || readinessUrl.isBlank()) { + return null; + } + try { + URI endpoint = URI.create(readinessUrl); + if (!("http".equals(endpoint.getScheme()) || "https".equals(endpoint.getScheme())) + || endpoint.getHost() == null + || endpoint.getUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || !"/actuator/health/readiness".equals(endpoint.getRawPath()) + || endpoint.getPort() == 0 + || endpoint.getPort() > 65535) { + return null; + } + return endpoint; + } catch (IllegalArgumentException ex) { + return null; + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java index d80266347a..b9a395bf82 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java @@ -1,16 +1,17 @@ package net.firedevops.firemud.gamesession.health; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; +import java.net.URI; import java.util.LinkedHashMap; import java.util.Map; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.common.health.DependencyReadinessSupport; +import net.firedevops.firemud.common.health.HttpEndpointAvailabilityChecker; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.GameLogicClient; +import net.firedevops.firemud.gamesession.config.GameLogicProperties; import net.firedevops.firemud.gamesession.health.GameplayLocalPathReadinessProbe.ProbeResult; import org.springframework.boot.health.contributor.HealthIndicator; import org.springframework.stereotype.Component; @@ -20,16 +21,18 @@ public class GameplayPathReadinessHealthIndicator implements HealthIndicator { private static final String COMPONENT = "game-session-service"; private static final String CONTRACT = "LOGIN->LOOK"; - private static final String PROBE_TENANT_ID = "1"; private static final String PROBE_EMAIL = "readiness-probe@example.invalid"; private static final String PROBE_PASSWORD = "invalid"; - private static final String PROBE_SESSION_ID = "1"; - private static final String PROBE_PLAYER_ID = "1"; - private static final String PROBE_GAME_INSTANCE_ID = "1"; - private static final String PROBE_ROOM_ID = "R-1021"; private final AccountClient accountClient; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Configuration properties are a framework-managed singleton") + private final GameLogicProperties gameLogicProperties; + + private final HttpEndpointAvailabilityChecker httpEndpointAvailabilityChecker; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected gRPC clients are framework-managed singletons and only stored") @@ -42,8 +45,12 @@ public GameplayPathReadinessHealthIndicator( AccountClient accountClient, GameLogicClient gameLogicClient, GameplayLocalPathReadinessProbe gameplayLocalPathReadinessProbe, - ReadinessTransitionTracker readinessTransitionTracker) { + ReadinessTransitionTracker readinessTransitionTracker, + GameLogicProperties gameLogicProperties, + HttpEndpointAvailabilityChecker httpEndpointAvailabilityChecker) { this.accountClient = accountClient; + this.gameLogicProperties = gameLogicProperties; + this.httpEndpointAvailabilityChecker = httpEndpointAvailabilityChecker; this.gameLogicClient = gameLogicClient; this.gameplayLocalPathReadinessProbe = gameplayLocalPathReadinessProbe; this.readinessTransitionTracker = readinessTransitionTracker; @@ -113,40 +120,25 @@ public org.springframework.boot.health.contributor.Health health() { "roundTrip", "redis:tick-queue", commandQueueProbe.detail())); try { - gameLogicClient.resolveLookForReadiness( - PROBE_TENANT_ID, - PROBE_SESSION_ID, - PROBE_PLAYER_ID, - PROBE_GAME_INSTANCE_ID, - PROBE_ROOM_ID); + var ping = gameLogicClient.pingForReadiness(); + if (ping == null || ping.hasError() || !"pong".equals(ping.getMessage())) { + throw new IllegalStateException("Game Logic authenticated Ping did not return pong"); + } + URI endpoint = gameLogicProperties.readinessEndpoint(); + if (endpoint == null || !httpEndpointAvailabilityChecker.isHealthy(endpoint)) { + throw new IllegalStateException( + "Game Logic dependency readiness unavailable or unconfigured"); + } dependencies.put( "gameLogicService", DependencyReadinessSupport.upDependency( - "resolveLook", "grpc:GameLogicService#ResolveLook", "OK")); - } catch (StatusRuntimeException ex) { - if (isReachableAppStatus(ex.getStatus().getCode())) { - dependencies.put( - "gameLogicService", - DependencyReadinessSupport.upDependency( - "resolveLook", - "grpc:GameLogicService#ResolveLook", - DependencyReadinessSupport.normalizeOutcome(ex.getStatus().getCode().name()))); - } else { - dependencies.put( - "gameLogicService", - DependencyReadinessSupport.downDependency( - "resolveLook", - "grpc:GameLogicService#ResolveLook", - DependencyReadinessSupport.message(ex))); - return DependencyReadinessSupport.recordOutOfService( - readinessTransitionTracker, COMPONENT, CONTRACT, "gameLogicService", dependencies); - } + "pingAndReadiness", "grpc:GameLogicService#Ping+http:actuator/readiness", "OK")); } catch (RuntimeException ex) { dependencies.put( "gameLogicService", DependencyReadinessSupport.downDependency( - "resolveLook", - "grpc:GameLogicService#ResolveLook", + "pingAndReadiness", + "grpc:GameLogicService#Ping+http:actuator/readiness", DependencyReadinessSupport.message(ex))); return DependencyReadinessSupport.recordOutOfService( readinessTransitionTracker, COMPONENT, CONTRACT, "gameLogicService", dependencies); @@ -155,8 +147,4 @@ public org.springframework.boot.health.contributor.Health health() { return DependencyReadinessSupport.recordUp( readinessTransitionTracker, COMPONENT, CONTRACT, dependencies); } - - private static boolean isReachableAppStatus(Status.Code code) { - return code == Status.Code.INVALID_ARGUMENT || code == Status.Code.NOT_FOUND; - } } diff --git a/services/game-session-service/src/main/resources/application-prod.yml b/services/game-session-service/src/main/resources/application-prod.yml index 6e40915a61..29d2e2ae89 100644 --- a/services/game-session-service/src/main/resources/application-prod.yml +++ b/services/game-session-service/src/main/resources/application-prod.yml @@ -41,6 +41,8 @@ management: enabled: true game: + logic: + readiness-url: ${GAME_LOGIC_READINESS_URL:} tick-duration-ms: ${GAME_TICK_DURATION_MS:1000} tick-max-commands: ${GAME_TICK_MAX_COMMANDS:50} diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index c9807bb544..34818a9da7 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -56,6 +56,7 @@ game: tick-max-commands: 50 logic: default-room-id: "R-1021" + readiness-url: ${GAME_LOGIC_READINESS_URL:http://game-logic-service:8080/actuator/health/readiness} firemud: start-session-operator-authorization: enabled: false diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index d2314e6379..69367ab3b6 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; import net.firedevops.firemud.test.AccountRuntimeStubServer; +import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; @@ -240,7 +241,13 @@ void websocketMovedPlayerStaysInGameAcrossGameLogicRestart() throws Exception { LookTestFixtures.DESTINATION_ROOM_ID) .test(response.trim())); + int gameLogicHttpPort = STACK.gameLogic().httpPort(); STACK.restartGameLogic(); + assertThat(STACK.gameLogic().httpPort()).isEqualTo(gameLogicHttpPort); + HttpTestSupport.awaitReadiness( + "http://localhost:" + gameLogicHttpPort + "/actuator/health/readiness", COMMAND_WAIT); + HttpTestSupport.awaitReadiness( + "http://localhost:" + gameSession().port() + "/actuator/health/readiness", COMMAND_WAIT); socket.send("LOOK"); socket.awaitMatching( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index c91a9c9043..1effab5ef4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -181,30 +181,54 @@ void resolveMoveForwardsGameInstanceIdIntoRoomInstance() throws Exception { } @Test - void resolveLookForReadinessUsesInternalProbeAttestation() throws Exception { - GameLogicClient client = newClient(); - GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = - mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); - when(stub.withDeadlineAfter(2L, TimeUnit.SECONDS)).thenReturn(stub); - when(stub.resolveLook( - LookRequest.newBuilder() - .setTenantId("22") - .setSessionId("41") - .setCharacterId("123") - .setRoomInstance( - RoomInstanceRef.newBuilder() - .setTenantId("22") - .setGameInstanceId("1") - .setRoomInstanceId("R-1021") - .build()) - .setSessionAttestation("probe-attestation") - .build())) - .thenReturn(LookResult.newBuilder().build()); + void readinessPingUsesShortDeadlineWithoutPlayerRequestOrAttestation() throws Exception { + var attestationService = mock(GameplaySessionAttestationService.class); + var client = + new GameLogicClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + attestationService); + var stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + var boundedStub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withDeadlineAfter(2L, TimeUnit.SECONDS)).thenReturn(boundedStub); + var expected = + net.firedevops.firemud.gamelogic.v1.PingResponse.newBuilder().setMessage("pong").build(); + when(boundedStub.ping(net.firedevops.firemud.gamelogic.v1.PingRequest.getDefaultInstance())) + .thenReturn(expected); setStub(client, stub); - client.resolveLookForReadiness("22", "41", "123", "1", "R-1021"); + assertThat(client.pingForReadiness()).isEqualTo(expected); + verify(stub).withDeadlineAfter(2L, TimeUnit.SECONDS); + verify(boundedStub).ping(net.firedevops.firemud.gamelogic.v1.PingRequest.getDefaultInstance()); + org.mockito.Mockito.verifyNoMoreInteractions(stub, boundedStub); + org.mockito.Mockito.verifyNoInteractions(attestationService); + } - assertThat(true).isTrue(); + @Test + void gameLogicStubRetainsConfiguredWorkloadCredentials() { + var credentials = mock(io.grpc.CallCredentials.class); + var customizer = + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withCallCredentials(credentials); + } + }; + var client = + new GameLogicClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + customizer, + mock(GameplaySessionAttestationService.class)); + + var stub = client.buildStub(mock(io.grpc.ManagedChannel.class)); + + assertThat(stub.getCallOptions().getCredentials()).isSameAs(credentials); + assertThat(stub.withDeadlineAfter(2L, TimeUnit.SECONDS).getCallOptions().getCredentials()) + .isSameAs(credentials); } @Test @@ -630,8 +654,6 @@ private static GameLogicClient newClient() { when(attestationService.issueGameplaySessionAttestation( "22", "41", "0", "123", "1", "R-2045", "world", "realm", "17", "SHARED")) .thenReturn("destination-attestation"); - when(attestationService.issueInternalProbeAttestation("22", "1", "R-1021")) - .thenReturn("probe-attestation"); return new GameLogicClient( new ServiceEndpointsProperties(), new CommonGrpcClientProperties(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameLogicPropertiesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameLogicPropertiesTest.java new file mode 100644 index 0000000000..c5767f7b4d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameLogicPropertiesTest.java @@ -0,0 +1,98 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.net.URI; +import java.util.Map; +import net.firedevops.firemud.gamesession.config.GameLogicProperties; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; + +class GameLogicPropertiesTest { + private GameLogicProperties bind(boolean production, Map overrides) + throws IOException { + StandardEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + var loader = new YamlPropertySourceLoader(); + for (var source : + loader.load("application", new FileSystemResource("src/main/resources/application.yml"))) { + environment.getPropertySources().addLast(source); + } + if (production) { + for (var source : + loader.load( + "production", new FileSystemResource("src/main/resources/application-prod.yml"))) { + environment.getPropertySources().addFirst(source); + } + } + environment.getPropertySources().addFirst(new MapPropertySource("overrides", overrides)); + return Binder.get(environment).bind("game.logic", Bindable.of(GameLogicProperties.class)).get(); + } + + @Test + void localConfigurationBindsInternalReadinessEndpoint() throws IOException { + assertThat(bind(false, Map.of()).readinessEndpoint()) + .isEqualTo(URI.create("http://game-logic-service:8080/actuator/health/readiness")); + } + + @Test + void productionRequiresExplicitEnvironmentBinding() throws IOException { + assertThat(bind(true, Map.of()).readinessEndpoint()).isNull(); + assertThat(bind(true, Map.of("GAME_LOGIC_READINESS_URL", "")).readinessEndpoint()).isNull(); + assertThat( + bind( + true, + Map.of( + "GAME_LOGIC_READINESS_URL", + "https://game-logic-service.internal:8443/actuator/health/readiness")) + .readinessEndpoint()) + .isEqualTo( + URI.create("https://game-logic-service.internal:8443/actuator/health/readiness")); + } + + @Test + void localOverrideUsesTheExplicitEnvironmentEndpoint() throws IOException { + assertThat( + bind( + false, + Map.of( + "GAME_LOGIC_READINESS_URL", + "http://logic.test:18080/actuator/health/readiness")) + .readinessEndpoint()) + .isEqualTo(URI.create("http://logic.test:18080/actuator/health/readiness")); + } + + @Test + void absentAndMalformedBindingsRemainUnusable() throws IOException { + assertThat(new GameLogicProperties().readinessEndpoint()).isNull(); + assertThat( + bind( + true, + Map.of( + "GAME_LOGIC_READINESS_URL", + "http://logic.test:0/actuator/health/readiness")) + .readinessEndpoint()) + .isNull(); + assertThat(bind(true, Map.of("GAME_LOGIC_READINESS_URL", "http://[bad")).readinessEndpoint()) + .isNull(); + assertThat( + bind( + true, + Map.of( + "GAME_LOGIC_READINESS_URL", + "http://logic.test:99999/actuator/health/readiness")) + .readinessEndpoint()) + .isNull(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java index 4a04070c69..87931ff58e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java @@ -1,163 +1,263 @@ package net.firedevops.firemud.gamesession.health; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import io.grpc.StatusRuntimeException; +import io.grpc.Status; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.net.URI; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.common.health.HttpEndpointAvailabilityChecker; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; +import net.firedevops.firemud.gamelogic.v1.PingResponse; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.GameLogicClient; +import net.firedevops.firemud.gamesession.config.GameLogicProperties; import net.firedevops.firemud.gamesession.health.GameplayLocalPathReadinessProbe.ProbeResult; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; -import org.springframework.boot.health.contributor.Health; -import org.springframework.boot.health.contributor.Status; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; class GameplayPathReadinessHealthIndicatorTest { + private static final String ENDPOINT = "http://game-logic-service:8080/actuator/health/readiness"; + private final AccountClient account = mock(AccountClient.class); + private final GameLogicClient gameLogic = mock(GameLogicClient.class); + private final GameplayLocalPathReadinessProbe local = mock(GameplayLocalPathReadinessProbe.class); + private final HttpEndpointAvailabilityChecker http = mock(HttpEndpointAvailabilityChecker.class); + private final GameLogicProperties properties = new GameLogicProperties(); - @Test - void healthReturnsUpWhenAccountAndGameLogicOperationsAreReachable() { - AccountClient accountClient = mock(AccountClient.class); - when(accountClient.authenticateForReadiness(anyString(), anyString())) + private GameplayPathReadinessHealthIndicator indicator() { + return new GameplayPathReadinessHealthIndicator( + account, + gameLogic, + local, + new ReadinessTransitionTracker(new SimpleMeterRegistry()), + properties, + http); + } + + private void healthyPrerequisites() { + when(account.authenticateForReadiness(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(AuthenticationErrorCodes.INVALID_CREDENTIALS) - .setMessage("Invalid credentials")) + ErrorDetail.newBuilder().setCode(AuthenticationErrorCodes.INVALID_CREDENTIALS)) .build()); - GameLogicClient gameLogicClient = mock(GameLogicClient.class); - doThrow(new StatusRuntimeException(io.grpc.Status.NOT_FOUND.withDescription("room missing"))) - .when(gameLogicClient) - .resolveLookForReadiness(anyString(), anyString(), anyString(), anyString(), anyString()); - GameplayLocalPathReadinessProbe localPathProbe = mock(GameplayLocalPathReadinessProbe.class); - when(localPathProbe.probeSessionContextStore()).thenReturn(ProbeResult.up("ROUND_TRIP_OK")); - when(localPathProbe.probeCommandQueueStore()).thenReturn(ProbeResult.up("QUEUE_WRITE_OK")); - GameplayPathReadinessHealthIndicator indicator = - new GameplayPathReadinessHealthIndicator( - accountClient, gameLogicClient, localPathProbe, tracker()); - - Health health = indicator.health(); - Object rawDependencies = Objects.requireNonNull(health.getDetails().get("dependencies")); - @SuppressWarnings("unchecked") - Map> dependencies = - (Map>) rawDependencies; + when(local.probeSessionContextStore()).thenReturn(ProbeResult.up("ROUND_TRIP_OK")); + when(local.probeCommandQueueStore()).thenReturn(ProbeResult.up("QUEUE_WRITE_OK")); + properties.setReadinessUrl(ENDPOINT); + when(gameLogic.pingForReadiness()) + .thenReturn(PingResponse.newBuilder().setMessage("pong").build()); + when(http.isHealthy(URI.create(ENDPOINT))).thenReturn(true); + } + + @ParameterizedTest + @CsvSource({"true,true", "true,false", "false,true", "false,false"}) + void requiresBothAuthenticatedPingAndDependencyReadiness(boolean ping, boolean readiness) { + healthyPrerequisites(); + if (!ping) { + when(gameLogic.pingForReadiness()).thenThrow(Status.UNAVAILABLE.asRuntimeException()); + } + when(http.isHealthy(URI.create(ENDPOINT))).thenReturn(readiness); + + var health = indicator().health(); - assertEquals(Status.UP, health.getStatus()); - assertIterableEquals( - List.of("contract", "admissionMeaning", "dependencies"), health.getDetails().keySet()); assertEquals( - "AUTH_INVALID_CREDENTIALS", - Objects.requireNonNull(dependencies.get("accountService")).get("outcome")); + ping && readiness + ? org.springframework.boot.health.contributor.Status.UP + : org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + health.getStatus()); + assertEquals("LOGIN->LOOK", health.getDetails().get("contract")); + @SuppressWarnings("unchecked") + var dependencies = + (java.util.Map>) + health.getDetails().get("dependencies"); assertEquals( - "NOT_FOUND", Objects.requireNonNull(dependencies.get("gameLogicService")).get("outcome")); + java.util.List.of( + "accountService", "sessionContextStore", "commandQueueStore", "gameLogicService"), + java.util.List.copyOf(dependencies.keySet())); + assertEquals("pingAndReadiness", dependencies.get("gameLogicService").get("check")); + if (!ping || !readiness) { + assertEquals("gameLogicService", health.getDetails().get("failingDependency")); + } + if (!ping) { + verifyNoInteractions(http); + } } - @Test - void healthReturnsOutOfServiceWhenAccountDependencyFails() { - AccountClient accountClient = mock(AccountClient.class); - doThrow(new IllegalStateException("account down")) - .when(accountClient) - .authenticateForReadiness(anyString(), anyString()); - GameplayPathReadinessHealthIndicator indicator = - new GameplayPathReadinessHealthIndicator( - accountClient, - mock(GameLogicClient.class), - mock(GameplayLocalPathReadinessProbe.class), - tracker()); - - Health health = indicator.health(); - Object rawDependencies = Objects.requireNonNull(health.getDetails().get("dependencies")); - @SuppressWarnings("unchecked") - Map> dependencies = - (Map>) rawDependencies; - - assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); - assertIterableEquals( - List.of("contract", "admissionMeaning", "dependencies", "failingDependency"), - health.getDetails().keySet()); - assertEquals("DOWN", Objects.requireNonNull(dependencies.get("accountService")).get("status")); + @ParameterizedTest + @ValueSource( + strings = {"INVALID_ARGUMENT", "NOT_FOUND", "PERMISSION_DENIED", "DEADLINE_EXCEEDED"}) + void rejectsEveryPingTransportFailure(String code) { + healthyPrerequisites(); + when(gameLogic.pingForReadiness()) + .thenThrow(Status.fromCode(Status.Code.valueOf(code)).asRuntimeException()); + assertEquals( + org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator().health().getStatus()); + verifyNoInteractions(http); } @Test - void healthReturnsOutOfServiceWhenGameLogicDependencyFails() { - AccountClient accountClient = mock(AccountClient.class); - when(accountClient.authenticateForReadiness(anyString(), anyString())) + void rejectsPingApplicationErrorEvenWhenMessageIsPong() { + healthyPrerequisites(); + when(gameLogic.pingForReadiness()) .thenReturn( - AuthenticateResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(AuthenticationErrorCodes.INVALID_CREDENTIALS) - .setMessage("Invalid credentials")) + PingResponse.newBuilder() + .setMessage("pong") + .setError(ErrorDetail.newBuilder().setCode("INTERNAL_ERROR")) .build()); - GameLogicClient gameLogicClient = mock(GameLogicClient.class); - doThrow(new StatusRuntimeException(io.grpc.Status.UNAVAILABLE.withDescription("logic down"))) - .when(gameLogicClient) - .resolveLookForReadiness(anyString(), anyString(), anyString(), anyString(), anyString()); - GameplayLocalPathReadinessProbe localPathProbe = mock(GameplayLocalPathReadinessProbe.class); - when(localPathProbe.probeSessionContextStore()).thenReturn(ProbeResult.up("ROUND_TRIP_OK")); - when(localPathProbe.probeCommandQueueStore()).thenReturn(ProbeResult.up("QUEUE_WRITE_OK")); - GameplayPathReadinessHealthIndicator indicator = - new GameplayPathReadinessHealthIndicator( - accountClient, gameLogicClient, localPathProbe, tracker()); - - Health health = indicator.health(); - Object rawDependencies = Objects.requireNonNull(health.getDetails().get("dependencies")); - @SuppressWarnings("unchecked") - Map> dependencies = - (Map>) rawDependencies; - - assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); - assertIterableEquals( - List.of("contract", "admissionMeaning", "dependencies", "failingDependency"), - health.getDetails().keySet()); - assertEquals("UP", Objects.requireNonNull(dependencies.get("accountService")).get("status")); assertEquals( - "DOWN", Objects.requireNonNull(dependencies.get("gameLogicService")).get("status")); + org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator().health().getStatus()); + verifyNoInteractions(http); } @Test - void healthReturnsOutOfServiceWhenLocalSessionContextProbeFails() { - AccountClient accountClient = mock(AccountClient.class); - when(accountClient.authenticateForReadiness(anyString(), anyString())) + void rejectsMissingOrUnexpectedPingResponse() { + healthyPrerequisites(); + for (PingResponse response : new PingResponse[] {null, PingResponse.getDefaultInstance()}) { + when(gameLogic.pingForReadiness()).thenReturn(response); + assertEquals( + org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator().health().getStatus()); + } + verifyNoInteractions(http); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "http://bad host/actuator/health/readiness", + "http://game-logic-service:8080/ping", + "ftp://game-logic-service/actuator/health/readiness", + "http://user@game-logic-service/actuator/health/readiness", + "http://game-logic-service/actuator/health/readiness?probe=1", + "http://game-logic-service/actuator/health/readiness#x" + }) + void rejectsUnconfiguredOrMalformedEndpointWithoutHttpRequest(String endpoint) { + healthyPrerequisites(); + properties.setReadinessUrl(endpoint); + assertEquals( + org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator().health().getStatus()); + verifyNoInteractions(http); + } + + @ParameterizedTest + @ValueSource(ints = {200, 401, 503}) + void actualHttpStatusIsRequiredAlongsidePing(int status) throws java.io.IOException { + healthyPrerequisites(); + var server = + com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0); + server.createContext( + "/actuator/health/readiness", + exchange -> { + exchange.sendResponseHeaders(status, -1); + exchange.close(); + }); + server.start(); + try { + properties.setReadinessUrl( + "http://127.0.0.1:" + server.getAddress().getPort() + "/actuator/health/readiness"); + var indicator = + new GameplayPathReadinessHealthIndicator( + account, + gameLogic, + local, + new ReadinessTransitionTracker(new SimpleMeterRegistry()), + properties, + new HttpEndpointAvailabilityChecker()); + assertEquals( + status == 200 + ? org.springframework.boot.health.contributor.Status.UP + : org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator.health().getStatus()); + } finally { + server.stop(0); + } + } + + @Test + void boundedHttpTimeoutFailsReadiness() throws java.io.IOException { + healthyPrerequisites(); + var release = new java.util.concurrent.CountDownLatch(1); + var server = + com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0); + server.createContext( + "/actuator/health/readiness", + exchange -> { + try { + release.await(4, java.util.concurrent.TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } finally { + exchange.close(); + } + }); + server.start(); + try { + properties.setReadinessUrl( + "http://127.0.0.1:" + server.getAddress().getPort() + "/actuator/health/readiness"); + var indicator = + new GameplayPathReadinessHealthIndicator( + account, + gameLogic, + local, + new ReadinessTransitionTracker(new SimpleMeterRegistry()), + properties, + new HttpEndpointAvailabilityChecker()); + assertEquals( + org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator.health().getStatus()); + } finally { + release.countDown(); + server.stop(0); + } + } + + @Test + void rejectsHttpCheckerFailure() { + healthyPrerequisites(); + when(http.isHealthy(any())).thenThrow(new IllegalArgumentException("invalid endpoint")); + assertEquals( + org.springframework.boot.health.contributor.Status.OUT_OF_SERVICE, + indicator().health().getStatus()); + } + + @Test + void preservesAccountUnavailableAndExceptionDenials() { + healthyPrerequisites(); + when(account.authenticateForReadiness(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(AuthenticationErrorCodes.INVALID_CREDENTIALS) - .setMessage("Invalid credentials")) + .setError(ErrorDetail.newBuilder().setCode(AuthenticationErrorCodes.UNAVAILABLE)) .build()); - GameplayLocalPathReadinessProbe localPathProbe = mock(GameplayLocalPathReadinessProbe.class); - when(localPathProbe.probeSessionContextStore()) - .thenReturn(ProbeResult.down("redis write failed")); - GameplayPathReadinessHealthIndicator indicator = - new GameplayPathReadinessHealthIndicator( - accountClient, mock(GameLogicClient.class), localPathProbe, tracker()); - - Health health = indicator.health(); - Object rawDependencies = Objects.requireNonNull(health.getDetails().get("dependencies")); - @SuppressWarnings("unchecked") - Map> dependencies = - (Map>) rawDependencies; - - assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); - assertIterableEquals( - List.of("contract", "admissionMeaning", "dependencies", "failingDependency"), - health.getDetails().keySet()); - assertEquals( - "DOWN", Objects.requireNonNull(dependencies.get("sessionContextStore")).get("status")); + assertEquals("accountService", indicator().health().getDetails().get("failingDependency")); + when(account.authenticateForReadiness(anyString(), anyString())) + .thenThrow(new IllegalStateException("account down")); + assertEquals("accountService", indicator().health().getDetails().get("failingDependency")); + verifyNoInteractions(gameLogic, http); } - private static ReadinessTransitionTracker tracker() { - return new ReadinessTransitionTracker(new SimpleMeterRegistry()); + @ParameterizedTest + @ValueSource(strings = {"sessionContextStore", "commandQueueStore"}) + void preservesLocalStoreDenials(String dependency) { + healthyPrerequisites(); + if ("sessionContextStore".equals(dependency)) { + when(local.probeSessionContextStore()).thenReturn(ProbeResult.down("redis down")); + } else { + when(local.probeCommandQueueStore()).thenReturn(ProbeResult.down("queue down")); + } + assertEquals(dependency, indicator().health().getDetails().get("failingDependency")); + verifyNoInteractions(gameLogic, http); } } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 841e7f873c..41e9d23b1a 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -99,20 +99,28 @@ public static GameLogicHolder startGameLogic( extraConfigClasses)) .run(toCommandLineArgs(props)); int boundGrpcPort = context.getBean(GrpcServerLifecycle.class).getPort(); - int restartGrpcPort = grpcPort == 0 ? boundGrpcPort : grpcPort; + int boundHttpPort = + Objects.requireNonNull(((WebServerApplicationContext) context).getWebServer()).getPort(); + Consumer> restartCustomizer = + restartProps -> { + customizer.accept(restartProps); + restartProps.put("server.port", String.valueOf(boundHttpPort)); + restartProps.put("spring.grpc.server.port", String.valueOf(boundGrpcPort)); + }; return new GameLogicHolder( context, boundGrpcPort, + boundHttpPort, worldEndpoint, entityEndpoint, socialEndpoint, () -> startGameLogic( - restartGrpcPort, + boundGrpcPort, worldEndpoint, entityEndpoint, socialEndpoint, - customizer, + restartCustomizer, extraConfigClasses)); } @@ -446,6 +454,7 @@ GameplayWorldCatalog defaultDemoTestGameplayWorldCatalog( public static final class GameLogicHolder { private final ConfigurableApplicationContext context; private final int grpcPort; + private final int httpPort; private final String worldEndpoint; private final String entityEndpoint; private final String socialEndpoint; @@ -454,12 +463,14 @@ public static final class GameLogicHolder { GameLogicHolder( ConfigurableApplicationContext context, int grpcPort, + int httpPort, String worldEndpoint, String entityEndpoint, String socialEndpoint, Supplier restartAction) { this.context = context; this.grpcPort = grpcPort; + this.httpPort = httpPort; this.worldEndpoint = worldEndpoint; this.entityEndpoint = entityEndpoint; this.socialEndpoint = socialEndpoint; @@ -470,6 +481,10 @@ public int grpcPort() { return grpcPort; } + public int httpPort() { + return httpPort; + } + public GameLogicHolder restart() { context.close(); return restartAction.get(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 7971ae90de..599c50c2f8 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -1191,6 +1191,9 @@ public GameplayCrossServiceStack start() throws IOException { props.put("firemud.postgres.username", postgresUsername); props.put("firemud.postgres.password", postgresPassword); props.put("firemud.database.enabled", "true"); + props.put( + "game.logic.readiness-url", + "http://localhost:" + gameLogic.httpPort() + "/actuator/health/readiness"); props.put("firemud.services.gameDesignService", gameDesignStub.endpoint()); props.put("firemud.services.entityManagementService", entityStub.endpoint()); if (socialStub != null) {