From 6486f3ee6bc13920065f7b6a7959b35a5aa65ca1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:31:01 +1300 Subject: [PATCH 01/22] Prepare exact Account Game Logic intake authorization and settlement --- .../account-service/api-contracts.md | 2 + .../gameplay-rules-entities-and-effects.md | 4 + .../player-access-and-session.md | 6 + .../v1/game_logic_intake_authorization.proto | 21 + ...e_logic_intake_authorization_service.proto | 36 + ...game_logic_intake_settlement_service.proto | 27 + ...ame_logic_intake_source_read_service.proto | 26 + .../v1/gameplay_rule_source_service.proto | 28 + protos/game-logic/v1/game_logic_service.proto | 10 + .../v1/gameplay_rule_intake_service.proto | 23 + ...ameplay_rule_intake_terminal_service.proto | 24 + ...meLogicIntakeAuthorizationGrpcService.java | 260 +++++ ...gicIntakeAuthorizationReadGrpcService.java | 55 + ...meLogicIntakeAuthorizationReadService.java | 66 ++ ...ameLogicIntakeAuthorizationRepository.java | 572 +++++++++ ...ntGameLogicIntakeAuthorizationService.java | 215 ++++ .../AccountGameLogicIntakeSettlement.java | 27 + ...tGameLogicIntakeSettlementGrpcService.java | 87 ++ ...countGameLogicIntakeSettlementService.java | 69 ++ ...tGameLogicIntakeSourceReadGrpcService.java | 94 ++ ...ountGameLogicIntakeSourceReadRecovery.java | 26 + ...countGameLogicIntakeSourceReadService.java | 96 ++ ...eAuthorizationPostgresIntegrationTest.java | 1028 +++++++++++++++++ ...gicIntakeAuthorizationGrpcServiceTest.java | 410 +++++++ ...ntakeAuthorizationReadGrpcServiceTest.java | 62 + ...eLogicIntakeAuthorizationRecoveryTest.java | 315 +++++ ...eLogicIntakeSettlementGrpcServiceTest.java | 313 +++++ ...eLogicIntakeSourceReadGrpcServiceTest.java | 231 ++++ ...tGameLogicIntakeSourceReadServiceTest.java | 61 + ...ldParticipationSettlementGrpcMtlsTest.java | 3 +- ...meLogicIntakeAuthorizationCredentials.java | 141 +++ ...ountGameLogicIntakeSettlementEvidence.java | 47 + ...ntGameLogicIntakeSettlementProtoCodec.java | 67 ++ ...ntGameLogicIntakeSettlementReadClient.java | 8 + ...GameLogicIntakeSettlementReadEvidence.java | 56 + .../GameLogicGameplayRuleIntakeOperation.java | 49 + .../GameLogicGameplayRuleIntakeTerminal.java | 170 +++ .../GameLogicIntakeAuthorizationBinding.java | 109 ++ .../GameLogicIntakeAuthorizationClient.java | 13 + .../GameLogicIntakeAuthorizationEvidence.java | 122 ++ ...GameLogicIntakeAuthorizationGrpcCodec.java | 141 +++ ...ameLogicIntakeAuthorizationReadClient.java | 156 +++ ...eLogicIntakeAuthorizationReadEvidence.java | 30 + ...LogicIntakeAuthorizationReadGrpcCodec.java | 59 + .../GameLogicIntakeRetainClient.java | 6 + .../GameLogicIntakeRetainEvidence.java | 83 ++ .../GameLogicIntakeRetainProtoCodec.java | 98 ++ .../GameLogicIntakeSourceReadClient.java | 6 + .../GameLogicIntakeSourceReadEvidence.java | 55 + .../GameLogicIntakeSourceReadProtoCodec.java | 89 ++ .../GameLogicIntakeSourceReadScope.java | 82 ++ .../GameLogicIntakeTerminalReadClient.java | 156 +++ .../GameLogicIntakeTerminalReadEvidence.java | 61 + .../GameLogicIntakeTerminalReadGrpcCodec.java | 83 ++ ...GameLogicPublicationSourceReadBinding.java | 247 ++++ ...meLogicPublicationSourceReadGrpcCodec.java | 358 ++++++ .../GameplayAbilitySchemaProjection.java | 185 +++ .../GameplayRuleSourceReadClient.java | 157 +++ .../GameplayRuleSourceReadEvidence.java | 153 +++ .../GameplayRuleSourceReadGrpcCodec.java | 94 ++ ...ntGameLogicIntakeSettlementReadClient.java | 156 +++ ...rpcGameLogicIntakeAuthorizationClient.java | 194 ++++ .../GrpcGameLogicIntakeRetainClient.java | 152 +++ .../GrpcGameLogicIntakeSourceReadClient.java | 159 +++ ...GameLogicIntakeSettlementReadGrpcTest.java | 711 ++++++++++++ ...LogicIntakeAuthorizationGrpcCodecTest.java | 277 +++++ .../GameLogicIntakeRetainProtoCodecTest.java | 384 ++++++ ...ameLogicIntakeSourceReadTransportTest.java | 755 ++++++++++++ .../GameLogicIntakeTerminalReadGrpcTest.java | 624 ++++++++++ ...LogicPublicationSourceReadBindingTest.java | 354 ++++++ ...gicPublicationSourceReadGrpcCodecTest.java | 437 +++++++ .../GameplayAbilitySchemaProjectionTest.java | 464 ++++++++ ...ogicIntakeAuthorizationClientMtlsTest.java | 450 ++++++++ ...pcGameLogicIntakeRetainClientMtlsTest.java | 383 ++++++ 74 files changed, 12776 insertions(+), 2 deletions(-) create mode 100644 protos/account/v1/game_logic_intake_authorization.proto create mode 100644 protos/account/v1/game_logic_intake_authorization_service.proto create mode 100644 protos/account/v1/game_logic_intake_settlement_service.proto create mode 100644 protos/account/v1/game_logic_intake_source_read_service.proto create mode 100644 protos/game-design/v1/gameplay_rule_source_service.proto create mode 100644 protos/game-logic/v1/gameplay_rule_intake_service.proto create mode 100644 protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 62ce6892a8..48accab778 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,6 +58,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. + Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. The initial private gameplay LOGIN owner, signer, registry, and response-recovery code is present as unregistered Account source, with focused proof sources. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. This does not add or activate an API, proto method, or Spring composition; the source has no caller-selected profile or property override. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact proof scope; deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, and runtime activation remain unproved. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 7a8b72e22c..b84d218491 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status +### Selected gameplay-rule intake prerequisite + +The prepared typed Account intake boundary carries a complete selected gameplay-rule source binding and immutable authorization, recovery and terminal-settlement evidence. It preserves the current stricter gameplay-rule manifest validation, including numeric stat values. Its Account unit/static/format and five PostgreSQL cases pass, and the corrected Common socket/static/format gate passes; exact scopes and earlier failed large-wire fixtures are attributed in the Account prerequisite tracker. Controlled upstream evidence is not genuine Game Design authoring or Game Logic retention. The actual Game Logic storage/terminal owner and Game Design selected-source/receipt pipeline remain absent from this cut and must qualify before the launch-descriptor producer can consume an intake receipt. Selected-full Entity schema 3 and Automation schema 6 convergence remains a separate unfinished producer/consumer obligation; retained release attestations 1–3 keep their original meaning. See the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) for owner and proof scope. + The live implementation is strongest in item containment and transfer, durable effect replay for requests carrying a nonblank `effectId`, and the first evaluated actor-state/effect seams. Entity mutation requests with a blank `effectId` still execute directly without the replay ledger; this compatibility path is not safe gameplay-admission proof, and focused replay/readiness remains blocked until ingress rejects blank IDs or supplies a valid trusted ID. Entity Management also has crafting-oriented query structures and version-scoped recipe rows, but there is no complete player crafting/material-consumption flow yet. The broader authored-action, generic actor, targeting, resource-cost, and combat models remain incomplete. Cross-service proof is strongest on the bounded item, LOOK, movement, and nonblank-effect replay paths; broader gameplay orchestration is still represented more by service-level tests and slice-oriented fixtures than by full production integration. Current residual: the crafting handlers remain runtime-reachable legacy implementation drift, but their paths and schemas are omitted from the authoritative Entity OpenAPI; the REST adapter is therefore unsupported/nonconformant rather than a public contract. The deployed Entity HTTP layer still requires only an `AUTHENTICATED` bearer and does not authorize that caller to the supplied tenant. It trusts caller-supplied tenant, recipe, and item identifiers. The existing crafting proof is happy-path only; tenant-qualified recipe lookup/update, same-tenant result/ingredient ownership, and cross-tenant negative proof remain open. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 0a349dc3b3..b93be0dcb4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Selected gameplay-rule intake authorization prerequisite + +The prepared Account source adds standalone Game Logic intake authorization, an immutable source-read reservation, exact finalized recovery, authorization reads, source reads and terminal settlement. It requires the same-namespace Game Design workload and current Account creator/environment evidence for fresh work. The actual selected Game Design source read precedes Account finalization; settlement independently reads the exact Game Logic terminal before Account SQL. Retained finalized recovery uses the original request and credential hash and never resumes a fresh source read. Common typed models, protobuf codecs and authenticated clients carry the complete immutable binding. The existing Account V95–V97 storage remains unchanged; these owners add no registration, route, enabling configuration or new SQL migration. + +Local qualification passes the Account check/static/format and all five focused PostgreSQL cases on the canonical PostgreSQL 18 image: 1,414 Account units have no failures or errors and four known skips; native cases have no failures, errors or skips. The namespace proof uses actual Account reservation/finalization and retained original scope, refuses cross-namespace HELD, terminal dispatch, settlement and replay, and preserves six intake tables including row metadata. R3 Common proof executes 630 cases with one oversized large-wire fixture failure; the other 625 cases outside that five-case class remain passing at R3. After correcting the bounded fixture, R5 freshly passes all five mTLS client cases and full Common static/format checks in 43s, including an actual response above the default 4MiB limit and within the 24MiB transport bound. The final receiving parent and proof-status documentation remain to qualify. The native Account fixture controls the upstream ORIGINAL AUTHOR readback; it does not prove genuine authoring, the Game Logic retention pipeline or end-to-end settlement. The actual Game Logic intake owner and Game Design receipt pipeline are the next dependency, followed by selected launch-descriptor production. This prerequisite closes no genuine Gameplay handoff and does not resume Unit 1B/corpus. Canonical authority remains in [Account API contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); the receiving source consequence is recorded in [Gameplay Rules](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-intake-prerequisite). + Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. diff --git a/protos/account/v1/game_logic_intake_authorization.proto b/protos/account/v1/game_logic_intake_authorization.proto new file mode 100644 index 0000000000..572e72deeb --- /dev/null +++ b/protos/account/v1/game_logic_intake_authorization.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Distinct immutable intake order. No original Draft/publication order or settlement is accepted. +service AccountGameLogicIntakeAuthorizationReadService { + rpc ReadHeldGameLogicIntakeAuthorization(ReadHeldGameLogicIntakeAuthorizationRequest) + returns (ReadHeldGameLogicIntakeAuthorizationResponse); +} +message ReadHeldGameLogicIntakeAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} +message ReadHeldGameLogicIntakeAuthorizationResponse { + ReadHeldGameLogicIntakeAuthorizationRequest request = 1; + bool held = 2; +} diff --git a/protos/account/v1/game_logic_intake_authorization_service.proto b/protos/account/v1/game_logic_intake_authorization_service.proto new file mode 100644 index 0000000000..35fa8e2448 --- /dev/null +++ b/protos/account/v1/game_logic_intake_authorization_service.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered Game Design producer for the distinct Game Logic intake order. +service AccountGameLogicIntakeAuthorizationService { + rpc AuthorizeIntake(GameLogicIntakeAuthorizationRequest) + returns (GameLogicIntakeAuthorizationResponse); + rpc RecoverIntake(GameLogicIntakeAuthorizationRequest) + returns (GameLogicIntakeAuthorizationResponse); + rpc AbortIntake(GameLogicIntakeAuthorizationRequest) + returns (GameLogicIntakeAuthorizationResponse); +} + +// The original creator credential is carried only in protected per-call metadata. +message GameLogicIntakeAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string transport_request_id = 3; + string intake_request_id = 4; + bytes selected_draft_binding = 5; +} + +message GameLogicIntakeAuthorizationResponse { + enum Outcome { + OUTCOME_UNSPECIFIED = 0; + RESERVED = 1; + FINALIZED = 2; + ABORTED = 3; + } + GameLogicIntakeAuthorizationRequest request = 1; + Outcome outcome = 2; + bytes preliminary_source_scope = 3; + bytes finalized_intake_authorization = 4; +} diff --git a/protos/account/v1/game_logic_intake_settlement_service.proto b/protos/account/v1/game_logic_intake_settlement_service.proto new file mode 100644 index 0000000000..9c276d1abd --- /dev/null +++ b/protos/account/v1/game_logic_intake_settlement_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only same-namespace Game Design may settle/recover. +// This is receipt production/recovery, never fresh intake or publication authorization. +service AccountGameLogicIntakeSettlementService { + rpc SettleGameLogicIntake(SettleGameLogicIntakeRequest) returns (SettleGameLogicIntakeResponse); +} + +message SettleGameLogicIntakeRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Transport correlation, separate from all durable intake identities. + string read_request_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} + +message SettleGameLogicIntakeResponse { + SettleGameLogicIntakeRequest request = 1; + // Complete immutable Account receipt, never a publication-operation identity. + bytes original_settlement_receipt = 2; + string settlement_receipt_digest = 3; +} diff --git a/protos/account/v1/game_logic_intake_source_read_service.proto b/protos/account/v1/game_logic_intake_source_read_service.proto new file mode 100644 index 0000000000..74cc9e11eb --- /dev/null +++ b/protos/account/v1/game_logic_intake_source_read_service.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Unregistered GD-only owner confirmation; canonical proof bytes are not permission. +service AccountGameLogicIntakeSourceReadService { + rpc ReadSourceScope(GameLogicIntakeSourcePermissionRequest) returns (GameLogicIntakeSourcePermissionResponse); + rpc ReadFinalizedIntake(GameLogicIntakeSourcePermissionRequest) returns (GameLogicIntakeSourcePermissionResponse); +} +message GameLogicIntakeSourcePermissionRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string purpose = 5; + oneof authorization_proof { + bytes preliminary_source_scope = 6; + bytes finalized_intake_authorization = 7; + } + string authorization_proof_digest = 8; +} +message GameLogicIntakeSourcePermissionResponse { + GameLogicIntakeSourcePermissionRequest request = 1; + bool permitted = 2; +} diff --git a/protos/game-design/v1/gameplay_rule_source_service.proto b/protos/game-design/v1/gameplay_rule_source_service.proto new file mode 100644 index 0000000000..8fb3a8c44b --- /dev/null +++ b/protos/game-design/v1/gameplay_rule_source_service.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; +package game_design.v1; +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Unregistered exact immutable synchronized source read, allowlisted to Account and GL. +service GameDesignGameplayRuleSourceReadService { + rpc ReadSelectedGameplayRuleSource(ReadSelectedGameplayRuleSourceRequest) + returns (ReadSelectedGameplayRuleSourceResponse); +} +message ReadSelectedGameplayRuleSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string game_design_binding_json = 4; + string game_design_binding_digest = 5; + oneof authorization_proof { + bytes preliminary_source_scope = 6; + bytes finalized_intake_authorization = 7; + } + string authorization_proof_digest = 8; + string purpose = 9; +} +message ReadSelectedGameplayRuleSourceResponse { + ReadSelectedGameplayRuleSourceRequest request = 1; + string complete_source_snapshot_json = 2; + string complete_source_snapshot_digest = 3; +} diff --git a/protos/game-logic/v1/game_logic_service.proto b/protos/game-logic/v1/game_logic_service.proto index 78c2086459..32f878da26 100644 --- a/protos/game-logic/v1/game_logic_service.proto +++ b/protos/game-logic/v1/game_logic_service.proto @@ -259,6 +259,9 @@ message GetDraftDesignDigestRequest { string publish_request_id = 5; string derived_workflow_identity = 6; string request_digest = 7; + // Distinct content selection; publicationDigestRequest/v1 remains unchanged. + bytes source_read_binding = 8; + string source_read_binding_digest = 9; } message GetDraftDesignDigestResponse { @@ -274,4 +277,11 @@ message GetDraftDesignDigestResponse { string script_patch_version = 8; } string base_version_id = 9; + bytes source_read_binding = 10; + string source_read_binding_digest = 11; + // Exact retained owner terminal; authorization alone is insufficient. + bytes retained_intake_terminal = 12; + string retained_intake_terminal_digest = 13; + string ability_schema_digest = 14; + string canonicalization = 15; } diff --git a/protos/game-logic/v1/gameplay_rule_intake_service.proto b/protos/game-logic/v1/gameplay_rule_intake_service.proto new file mode 100644 index 0000000000..42ec1255f3 --- /dev/null +++ b/protos/game-logic/v1/gameplay_rule_intake_service.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +package game_logic.v1; +option java_package = "net.firedevops.firemud.gamelogic.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the exact same-namespace Game Design workload may request +// retention under an original, distinct Account intake authorization. +service GameLogicGameplayRuleIntakeService { + rpc RetainGameplayRuleIntake(RetainGameplayRuleIntakeRequest) + returns (RetainGameplayRuleIntakeResponse); +} +message RetainGameplayRuleIntakeRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string correlation_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} +message RetainGameplayRuleIntakeResponse { + RetainGameplayRuleIntakeRequest request = 1; + bytes original_terminal = 2; + string terminal_digest = 3; +} diff --git a/protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto b/protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto new file mode 100644 index 0000000000..ed6dce8134 --- /dev/null +++ b/protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; +package game_logic.v1; +option java_package = "net.firedevops.firemud.gamelogic.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the same-namespace Account workload may read. +service GameLogicGameplayRuleIntakeTerminalReadService { + rpc ReadGameplayRuleIntakeTerminal(ReadGameplayRuleIntakeTerminalRequest) returns (ReadGameplayRuleIntakeTerminalResponse); +} +message ReadGameplayRuleIntakeTerminalRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} +message ReadGameplayRuleIntakeTerminalResponse { + ReadGameplayRuleIntakeTerminalRequest request = 1; + oneof result { + bool absent = 2; + bytes original_terminal = 3; + } + string terminal_digest = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java new file mode 100644 index 0000000000..3b72c49cca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java @@ -0,0 +1,260 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered same-namespace Game Design intake authorization producer. */ +public final class AccountGameLogicIntakeAuthorizationGrpcService implements BindableService { + private final AccountGameLogicIntakeAuthorizationService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountGameLogicIntakeAuthorizationGrpcService( + AccountGameLogicIntakeAuthorizationService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** Peer authentication precedes protected metadata parsing and all request decoding. */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceImplBase() { + @Override + public void authorizeIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + AccountGameLogicIntakeAuthorizationGrpcService.this.authorizeIntake(request, observer); + } + + @Override + public void recoverIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + AccountGameLogicIntakeAuthorizationGrpcService.this.recoverIntake(request, observer); + } + + @Override + public void abortIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + AccountGameLogicIntakeAuthorizationGrpcService.this.abortIntake(request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + String method = call.getMethodDescriptor().getFullMethodName(); + if (!AccountGameLogicIntakeAuthorizationCredentials.allowedMethod(method)) { + call.close(sanitized(Status.UNIMPLEMENTED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountGameLogicIntakeAuthorizationCredentials.Credential credential; + try { + credential = + AccountGameLogicIntakeAuthorizationCredentials.readAuthenticated(headers, method); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeIntake( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + final AuthenticatedRequest authenticated; + try { + authenticated = request(wire); + } catch (StatusRuntimeException denied) { + deny(observer, Status.fromCode(denied.getStatus().getCode())); + return; + } + var request = authenticated.request(); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final GameLogicIntakeAuthorizationResponse response; + try { + var authorization = + owner.authorizeWithEnvironmentCapture( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.selected(), + terms::captureCurrentEnvironmentBoundary); + response = + GameLogicIntakeAuthorizationGrpcCodec.toResponse( + GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization)); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + public void recoverIntake( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + var authenticated = parseRequest(wire, observer); + if (authenticated == null) return; + var request = authenticated.request(); + final GameLogicIntakeAuthorizationResponse response; + try { + var recovery = + owner.recover( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.selected()); + response = GameLogicIntakeAuthorizationGrpcCodec.toResponse(recovered(request, recovery)); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + public void abortIntake( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + var authenticated = parseRequest(wire, observer); + if (authenticated == null) return; + var request = authenticated.request(); + final GameLogicIntakeAuthorizationResponse response; + try { + var recovery = + owner.abortSourceRead( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.selected()); + response = GameLogicIntakeAuthorizationGrpcCodec.toResponse(recovered(request, recovery)); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private AuthenticatedRequest parseRequest( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + try { + var authenticated = request(wire); + var request = authenticated.request(); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return null; + } + return authenticated; + } catch (StatusRuntimeException denied) { + deny(observer, Status.fromCode(denied.getStatus().getCode())); + return null; + } + } + + private AuthenticatedRequest request(GameLogicIntakeAuthorizationRequest wire) { + Status denied = peerDenial(); + if (denied != null) throw sanitized(denied).asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw sanitized(Status.FAILED_PRECONDITION).asRuntimeException(); + var protectedCredential = AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + final String credential; + try { + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + } + try { + return new AuthenticatedRequest( + GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wire), credential); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.INVALID_ARGUMENT).asRuntimeException(); + } + } + + private static GameLogicIntakeAuthorizationEvidence.Result recovered( + GameLogicIntakeAuthorizationEvidence.Request request, + AccountGameLogicIntakeSourceReadRecovery recovery) { + return new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.valueOf(recovery.state().name()), + java.util.Optional.of(recovery.scope()), + recovery.authorization()); + } + + private record AuthenticatedRequest( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + @Override + public String toString() { + return "AuthenticatedGameLogicIntakeAuthorizationRequest[redacted]"; + } + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status statusOf(RuntimeException error) { + if (error instanceof StatusRuntimeException status) + return Status.fromCode(status.getStatus().getCode()); + if (error instanceof IllegalArgumentException) return Status.FAILED_PRECONDITION; + return Status.UNAVAILABLE; + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private static Status sanitized(Status status) { + return status.withDescription("Account Game Logic intake authorization denied or unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..9d753285f8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadGrpcCodec; + +/** Standalone only; authenticate exact workload before parsing a caller-carried binding. */ +public final class AccountGameLogicIntakeAuthorizationReadGrpcService + extends AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceImplBase { + private final AccountGameLogicIntakeAuthorizationReadService owner; + private final String namespace; + + public AccountGameLogicIntakeAuthorizationReadGrpcService( + AccountGameLogicIntakeAuthorizationReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readHeldGameLogicIntakeAuthorization( + ReadHeldGameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + try { + AccountGameLogicIntakeAuthorizationReadService.requirePeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence.Request + decoded; + try { + decoded = GameLogicIntakeAuthorizationReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + owner.requireHeld(decoded); + observer.onNext(GameLogicIntakeAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java new file mode 100644 index 0000000000..d4410c83e9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered exact held-source read; settled orders cannot mint fresh HELD evidence. */ +public final class AccountGameLogicIntakeAuthorizationReadService { + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected repository is an intentionally shared service collaborator.") + public AccountGameLogicIntakeAuthorizationReadService( + AccountGameLogicIntakeAuthorizationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public void requireHeld(GameLogicIntakeAuthorizationReadEvidence.Request request) { + requirePeer(namespace); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + try { + transaction.execute( + ignored -> { + repository.readHeld(request.binding(), namespace); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException changed) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (!(prefix + "game-logic-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java new file mode 100644 index 0000000000..2557d1aded --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java @@ -0,0 +1,572 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable intake orders, exact terminal settlements, and full original source participation. */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") +public final class AccountGameLogicIntakeAuthorizationRepository { + private final DSLContext dsl; + + public AccountGameLogicIntakeAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + GameLogicIntakeSourceReadScope reserveSourceRead( + UUID requestId, + net.firedevops.firemud.common.authoring.DraftCommitBinding selected, + AccountControlUiActorService.Current current, + String namespace, + Runnable admission) { + requireTransaction(); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE tenant_uuid = ? AND intake_request_id = ? FOR UPDATE", + current.stored().tenantId, + requestId); + if (row != null) { + var original = + GameLogicIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + if (!namespace.equals(original.targetNamespace()) + || !original.actorAccountId().equals(current.stored().accountId) + || !original.selected().equals(selected)) + throw new IllegalArgumentException("Intake request identity conflicts with original scope"); + requireReservation(row, original); + requireCurrentReservation(row, current); + if (aborted(original)) throw new IllegalStateException("Original source-read scope aborted"); + return original; + } + admission.run(); + var scope = + new GameLogicIntakeSourceReadScope( + namespace, + UUID.randomUUID(), + UUID.randomUUID(), + requestId, + current.stored().accountId, + selected, + "spiffe://firemud/ns/" + namespace + "/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, tenant_uuid, version_uuid, " + + "scope_bytes, scope_digest, issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scope.operationId(), + scope.fenceId(), + requestId, + scope.actorAccountId(), + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + scope.canonicalBytes(), + scope.digest(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var source : current.source().sources()) + dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + scope.operationId(), + source.key(), + source.canonicalBytes()); + requireReservation(reservation(scope), scope); + return scope; + } + + GameLogicIntakeAuthorizationBinding finalizeSourceRead( + GameLogicIntakeSourceReadScope scope, + GameplayRuleSelectedSource source, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + var reserved = reservation(scope); + requireReservation(reserved, scope); + requireCurrentReservation(reserved, current); + if (!scope.selected().equals(source.binding())) + throw new IllegalArgumentException("Source differs from original selected scope"); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + scope.operationId()); + if (row != null) { + var original = + GameLogicIntakeAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + if (!original.source().equals(source)) + throw new IllegalArgumentException( + "Intake request identity conflicts with original source"); + requireExact(row, original); + return original; + } + admission.run(); + var binding = + new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + scope.actorAccountId(), + source, + current.source().sources()); + dsl.execute( + "INSERT INTO account_game_logic_intake_authorizations (operation_id, fence_id, actor_account_uuid, " + + "tenant_uuid, version_uuid, intake_request_id, source_digest, binding, issuance_operation_id, " + + "issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + scope.intakeRequestId(), + source.digest(), + binding.canonicalBytes(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var value : binding.sources()) + dsl.execute( + "INSERT INTO account_game_logic_intake_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + value.key(), + value.canonicalBytes()); + requireExact( + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + binding.operationId()), + binding); + return binding; + } + + AccountGameLogicIntakeSourceReadRecovery recoverSourceRead(GameLogicIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + var row = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + scope.operationId()); + var state = AccountGameLogicIntakeSourceReadRecovery.State.RESERVED; + java.util.Optional result = java.util.Optional.empty(); + if (row != null) { + state = AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED; + var finalOrder = + GameLogicIntakeAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + if (!scope.operationId().equals(finalOrder.operationId()) + || !scope.fenceId().equals(finalOrder.fenceId()) + || !scope.intakeRequestId().equals(finalOrder.intakeRequestId()) + || !scope.actorAccountId().equals(finalOrder.actorAccountId()) + || !scope.selected().equals(finalOrder.source().binding())) + throw new IllegalArgumentException("Finalized order differs from original scope"); + result = java.util.Optional.of(finalOrder); + } else if (aborted(scope)) state = AccountGameLogicIntakeSourceReadRecovery.State.ABORTED; + return new AccountGameLogicIntakeSourceReadRecovery(scope, state, result); + } + + java.util.Optional findSourceReadScope( + UUID requestId, + net.firedevops.firemud.common.authoring.DraftCommitBinding selected, + String namespace, + String originalTokenHash) { + requireTransaction(); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE tenant_uuid = ? AND intake_request_id = ?", + selected.target().canonicalTenantId(), + requestId); + if (row == null) return java.util.Optional.empty(); + var scope = GameLogicIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + requireReservation(row, scope); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + row.get("issuance_operation_id", UUID.class)); + if (!namespace.equals(scope.targetNamespace()) + || !selected.equals(scope.selected()) + || !originalTokenHash.equals( + new AccountControlUiIssuanceRepository.Stored(issuer).tokenHash)) + throw new IllegalArgumentException( + "Intake request conflicts with original actor credential or selection"); + return java.util.Optional.of(scope); + } + + AccountGameLogicIntakeSourceReadRecovery abortSourceRead(GameLogicIntakeSourceReadScope scope) { + var original = recoverSourceRead(scope); + if (original.state() == AccountGameLogicIntakeSourceReadRecovery.State.RESERVED) + dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_aborts (operation_id) VALUES (?)", + scope.operationId()); + return recoverSourceRead(scope); + } + + record SourceReadCurrentness(String tokenHash, String registryDigest, long expiresAt) {} + + SourceReadCurrentness sourceReadCurrentness(GameLogicIntakeSourceReadScope scope) { + requireTransaction(); + // No locks survive this transaction or the following remote registry read. + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + scope.operationId()); + if (row == null) + throw new IllegalArgumentException("Original preliminary scope absent or changed"); + requireReservation(row, scope); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + row.get("issuance_operation_id", UUID.class)); + if (issuer == null) throw new IllegalStateException("Original creator issuance absent"); + var stored = new AccountControlUiIssuanceRepository.Stored(issuer); + if (!"COMMITTED".equals(stored.status)) + throw new IllegalStateException("Original creator issuance is no longer current"); + return new SourceReadCurrentness( + stored.tokenHash, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + stored.activeRegistry), + stored.expiresAt.getEpochSecond()); + } + + void readSourceScope( + GameLogicIntakeSourceReadScope scope, SourceReadCurrentness expected, java.time.Instant now) { + var recovered = recoverSourceRead(scope); + if (recovered.state() != AccountGameLogicIntakeSourceReadRecovery.State.RESERVED + || !sourceReadCurrentness(scope).equals(expected) + || now.getEpochSecond() >= expected.expiresAt()) + throw new IllegalStateException("Exact current held preliminary scope required"); + } + + void readFinalizedSourceScope( + GameLogicIntakeAuthorizationBinding authorization, String namespace) { + requireTransaction(); + var scope = requireOriginalScope(authorization, namespace); + var recovered = recoverSourceRead(scope); + if (recovered.authorization().isEmpty() + || !Arrays.equals( + authorization.canonicalBytes(), + recovered.authorization().orElseThrow().canonicalBytes())) + throw new IllegalArgumentException("Exact finalized intake authorization required"); + readHeld(authorization, namespace); + } + + /** Original namespace and order are checked before selecting authority locks or dispatching. */ + private GameLogicIntakeSourceReadScope requireOriginalScope( + GameLogicIntakeAuthorizationBinding requested, String namespace) { + requireTransaction(); + var order = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + requested.operationId()); + if (order == null + || !Arrays.equals(requested.canonicalBytes(), order.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + requested.operationId()); + if (row == null) throw new IllegalArgumentException("Original source-read reservation absent"); + var scope = GameLogicIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + requireReservation(row, scope); + if (!scope.targetNamespace().equals(namespace)) + throw new IllegalArgumentException("Changed original source namespace"); + if (!scope.operationId().equals(requested.operationId()) + || !scope.fenceId().equals(requested.fenceId()) + || !scope.intakeRequestId().equals(requested.intakeRequestId()) + || !scope.actorAccountId().equals(requested.actorAccountId()) + || !scope.selected().equals(requested.source().binding())) + throw new IllegalArgumentException("Finalized order differs from original scope"); + return scope; + } + + private Record reservation(GameLogicIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ? FOR UPDATE", + scope.operationId()); + } + + private boolean aborted(GameLogicIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_source_read_aborts WHERE operation_id = ?", + scope.operationId()) + != null; + } + + private void lockReservedSources(GameLogicIntakeSourceReadScope scope) { + // Reject changed caller bytes before using the retained original's sorted lock vector. + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + scope.operationId()); + requireReservation(row, scope); + for (var value : + dsl.fetch( + "SELECT source_key FROM account_game_logic_intake_source_read_sources WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId())) + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + value.get("source_key", String.class)) + == null) throw new IllegalStateException("Original preliminary source lock absent"); + } + + private static void requireCurrentReservation( + Record row, AccountControlUiActorService.Current current) { + if (!current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class))) + throw new IllegalArgumentException("Changed original intake creator authority"); + } + + private void requireReservation(Record row, GameLogicIntakeSourceReadScope scope) { + if (row == null + || !Arrays.equals(scope.canonicalBytes(), row.get("scope_bytes", byte[].class)) + || !scope.digest().equals(row.get("scope_digest", String.class)) + || !scope.operationId().equals(row.get("operation_id", UUID.class)) + || !scope.fenceId().equals(row.get("fence_id", UUID.class)) + || !scope.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !scope.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !scope.selected().target().canonicalTenantId().equals(row.get("tenant_uuid", UUID.class)) + || !scope + .selected() + .target() + .canonicalVersionId() + .equals(row.get("version_uuid", UUID.class))) + throw new IllegalArgumentException("Original preliminary scope absent or changed"); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + row.get("issuance_operation_id", UUID.class)); + if (issuer == null) throw new IllegalStateException("Original creator issuance absent"); + var original = new AccountControlUiIssuanceRepository.Stored(issuer); + if (!scope.actorAccountId().equals(original.accountId) + || !scope.selected().target().canonicalTenantId().equals(original.tenantId) + || !Arrays.equals(original.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(original.bundle, row.get("issuance_bundle", byte[].class))) + throw new IllegalArgumentException("Changed preliminary creator evidence"); + var vector = AccountControlUiIssuanceRepository.object(original.sources).get("sources"); + var held = + dsl.fetch( + "SELECT source_key, source_evidence FROM account_game_logic_intake_source_read_sources WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId()); + if (!(vector instanceof java.util.List values) + || values.isEmpty() + || held.size() != values.size()) + throw new IllegalArgumentException("Incomplete preliminary source participation"); + for (int i = 0; i < held.size(); i++) { + var bytes = java.util.Base64.getDecoder().decode((String) values.get(i)); + var source = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence + .fromStored(bytes); + if (!source.key().equals(held.get(i).get("source_key", String.class)) + || !Arrays.equals(bytes, held.get(i).get("source_evidence", byte[].class))) + throw new IllegalArgumentException("Changed preliminary source participation"); + } + } + + public void readHeld(GameLogicIntakeAuthorizationBinding requested, String namespace) { + requireTransaction(); + requireOriginalScope(requested, namespace); + // Deny a changed lookup before acquiring caller-selected authority locks. + var lookup = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + requested.operationId()); + if (lookup == null + || !Arrays.equals(requested.canonicalBytes(), lookup.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var original = + GameLogicIntakeAuthorizationBinding.fromStored(lookup.get("binding", byte[].class)); + for (var value : original.sources()) + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + value.key()) + == null) throw new IllegalArgumentException("Original intake source lock absent"); + requireExact( + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + original.operationId()), + original); + if (dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_settlements WHERE operation_id = ?", + original.operationId()) + != null) throw new IllegalArgumentException("Original intake order already settled"); + } + + /** Only called after the producer's authenticated GL read, with no remote read under locks. */ + java.util.Optional findSettlement( + GameLogicIntakeAuthorizationBinding requested, String namespace) { + requireTransaction(); + requireOriginalScope(requested, namespace); + var order = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + requested.operationId()); + if (order == null + || !Arrays.equals(requested.canonicalBytes(), order.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_settlements WHERE operation_id = ?", + requested.operationId()); + if (row == null) return java.util.Optional.empty(); + var receipt = + AccountGameLogicIntakeSettlement.fromStored(row.get("receipt_bytes", byte[].class)); + if (!namespace.equals(receipt.terminal().operation().targetNamespace()) + || !Arrays.equals(requested.canonicalBytes(), receipt.terminal().authorizationBytes())) + throw new IllegalArgumentException("Changed exact intake settlement"); + return java.util.Optional.of(exactSettlement(row, receipt)); + } + + /** Only called after the producer's authenticated GL read, with no remote read under locks. */ + AccountGameLogicIntakeSettlement settle(AccountGameLogicIntakeSettlement requested) { + requireTransaction(); + var binding = requested.terminal().operation().authorization(); + requireOriginalScope(binding, requested.terminal().operation().targetNamespace()); + var lookup = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + binding.operationId()); + if (lookup == null + || !Arrays.equals(binding.canonicalBytes(), lookup.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + // The retained original determines the sorted locks, never an unchecked caller source vector. + var original = + GameLogicIntakeAuthorizationBinding.fromStored(lookup.get("binding", byte[].class)); + for (var source : original.sources()) + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.key()) + == null) throw new IllegalArgumentException("Original intake source lock absent"); + var order = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + original.operationId()); + if (order == null + || !Arrays.equals(original.canonicalBytes(), order.get("binding", byte[].class))) + throw new IllegalArgumentException("Changed original intake order"); + var prior = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_settlements WHERE operation_id = ? FOR UPDATE", + original.operationId()); + if (prior != null) return exactSettlement(prior, requested); + requireExact(order, original); + var terminal = requested.terminal(); + dsl.execute( + "INSERT INTO account_game_logic_intake_settlements (operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + original.operationId(), + terminal.operation().targetNamespace(), + terminal.outcome().name(), + terminal.canonicalBytes(), + terminal.digest(), + requested.canonicalBytes(), + requested.digest()); + return exactSettlement( + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_settlements WHERE operation_id = ? FOR UPDATE", + original.operationId()), + requested); + } + + private static AccountGameLogicIntakeSettlement exactSettlement( + Record row, AccountGameLogicIntakeSettlement requested) { + if (row == null) throw new IllegalStateException("Settlement commit readback absent"); + var original = + AccountGameLogicIntakeSettlement.fromStored(row.get("receipt_bytes", byte[].class)); + var terminal = original.terminal(); + if (!Arrays.equals(original.canonicalBytes(), requested.canonicalBytes()) + || !original.digest().equals(row.get("receipt_digest", String.class)) + || !terminal.digest().equals(row.get("terminal_digest", String.class)) + || !Arrays.equals(terminal.canonicalBytes(), row.get("terminal_bytes", byte[].class)) + || !terminal + .operation() + .authorization() + .operationId() + .equals(row.get("operation_id", UUID.class)) + || !terminal.operation().targetNamespace().equals(row.get("target_namespace", String.class)) + || !terminal.outcome().name().equals(row.get("outcome", String.class))) + throw new IllegalArgumentException("Changed exact intake settlement"); + return original; + } + + private void requireExact(Record row, GameLogicIntakeAuthorizationBinding binding) { + if (row == null + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !binding.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.versionId().equals(row.get("version_uuid", UUID.class)) + || !binding.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !binding.source().digest().equals(row.get("source_digest", String.class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ? FOR UPDATE NOWAIT", + row.get("issuance_operation_id", UUID.class)); + if (issuer == null) throw new IllegalArgumentException("Original committed issuance absent"); + var original = new AccountControlUiIssuanceRepository.Stored(issuer); + // Source-writer guards prevent revocation while this operation participates. + if (!"COMMITTED".equals(original.status) + || !binding.actorAccountId().equals(original.accountId) + || !binding.tenantId().equals(original.tenantId) + || !Arrays.equals(original.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(original.bundle, row.get("issuance_bundle", byte[].class))) + throw new IllegalArgumentException("Changed original intake issuance"); + var bundle = AccountControlUiIssuanceRepository.object(original.bundle); + var payload = AccountControlUiIssuanceRepository.object(original.sources); + if (!(bundle.get("issuanceFence") instanceof Number fence) + || fence.longValue() != row.get("issuance_fence", Long.class) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + bundle.get("outboxCheckpoints")), + row.get("outbox_checkpoints", byte[].class)) + || !(payload.get("sources") instanceof java.util.List vector) + || vector.size() != binding.sources().size()) + throw new IllegalArgumentException("Incomplete original issuance vector"); + var participation = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_game_logic_intake_sources WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(v -> v.get("source_key", String.class))) + .toList(); + if (participation.size() != binding.sources().size()) + throw new IllegalArgumentException("Incomplete intake participation"); + for (int i = 0; i < participation.size(); i++) { + var source = binding.sources().get(i); + if (!(vector.get(i) instanceof String encoded) + || !Arrays.equals(source.canonicalBytes(), java.util.Base64.getDecoder().decode(encoded)) + || !source.key().equals(participation.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), participation.get(i).get("source_evidence", byte[].class))) + throw new IllegalArgumentException("Changed intake participation"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw new IllegalStateException("Writable Account owner transaction required"); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw new IllegalStateException( + "Writable READ_COMMITTED Account owner transaction required"); + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java new file mode 100644 index 0000000000..0ede8e79fe --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java @@ -0,0 +1,215 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered distinct intake producer. Genuine current creator and GD owner reads are mandatory. + */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner transaction collaborators.") +public final class AccountGameLogicIntakeAuthorizationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final GameplayRuleSourceReadClient sources; + private final String namespace; + private final TransactionTemplate transaction; + + public AccountGameLogicIntakeAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountGameLogicIntakeAuthorizationRepository repository, + GameplayRuleSourceReadClient sources, + PlatformTransactionManager transactions, + String namespace) { + this.actors = Objects.requireNonNull(actors); + this.fences = Objects.requireNonNull(fences); + this.repository = Objects.requireNonNull(repository); + this.sources = Objects.requireNonNull(sources); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + public GameLogicIntakeAuthorizationBinding authorize( + String compactJwt, + UUID intakeRequestId, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + return authorizeWithEnvironmentCapture( + compactJwt, intakeRequestId, selected, () -> environment); + } + + /** + * Exact finalized recovery precedes mutable environment capture. New work captures authority for + * reservation, then captures it again after the remote source read before finalization. + */ + public GameLogicIntakeAuthorizationBinding authorizeWithEnvironmentCapture( + String compactJwt, + UUID intakeRequestId, + DraftCommitBinding selected, + Supplier environmentCapture) { + requirePeer(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( + intakeRequestId); + Objects.requireNonNull(selected); + Objects.requireNonNull(environmentCapture); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Source read must precede Account SQL") + .asRuntimeException(); + var retained = findScope(compactJwt, intakeRequestId, selected); + if (retained.isPresent()) { + var original = recover(retained.orElseThrow()); + if (original.authorization().isPresent()) return original.authorization().orElseThrow(); + if (original.state() == AccountGameLogicIntakeSourceReadRecovery.State.ABORTED) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + var environment = Objects.requireNonNull(environmentCapture.get()); + var scope = reserveSourceRead(compactJwt, intakeRequestId, selected, environment); + var recovered = recover(scope); + if (recovered.authorization().isPresent()) return recovered.authorization().orElseThrow(); + if (recovered.state() != AccountGameLogicIntakeSourceReadRecovery.State.RESERVED) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + var request = GameplayRuleSourceReadEvidence.Request.forAccountSourceScope(namespace, scope); + var evidence = sources.read(request); + if (evidence == null + || !request.equals(evidence.request()) + || !selected.equals(evidence.source().binding())) + throw new IllegalStateException("Exact authenticated complete GD source required"); + var finalizationEnvironment = Objects.requireNonNull(environmentCapture.get()); + return actors.withCurrent( + compactJwt, + selected.target().canonicalTenantId(), + finalizationEnvironment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return repository.finalizeSourceRead( + scope, + evidence.source(), + current, + () -> fences.requireGameLogicIntakeAdmission(current.source().sources(), selected)); + }); + } + + public GameLogicIntakeSourceReadScope reserveSourceRead( + String compactJwt, + UUID intakeRequestId, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + requirePeer(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( + intakeRequestId); + Objects.requireNonNull(selected); + outsideSql(); + return actors.withCurrent( + compactJwt, + selected.target().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return repository.reserveSourceRead( + intakeRequestId, + selected, + current, + namespace, + () -> fences.requireGameLogicIntakeAdmission(current.source().sources(), selected)); + }); + } + + /** Exact original evidence, including after creator expiry; never resumes a source read. */ + public AccountGameLogicIntakeSourceReadRecovery recover(GameLogicIntakeSourceReadScope scope) { + requirePeer(); + requireScope(scope); + outsideSql(); + return transaction.execute(ignored -> repository.recoverSourceRead(scope)); + } + + /** + * Recovers a lost first response using the exact original request and retained credential hash. + */ + public AccountGameLogicIntakeSourceReadRecovery recover( + String originalCompactJwt, UUID intakeRequestId, DraftCommitBinding selected) { + return recover( + findScope(originalCompactJwt, intakeRequestId, selected) + .orElseThrow( + () -> new IllegalArgumentException("Original source-read reservation absent"))); + } + + /** A definitive preliminary abort excludes any late finalization of this same operation. */ + public AccountGameLogicIntakeSourceReadRecovery abortSourceRead( + GameLogicIntakeSourceReadScope scope) { + requirePeer(); + requireScope(scope); + outsideSql(); + return transaction.execute(ignored -> repository.abortSourceRead(scope)); + } + + public AccountGameLogicIntakeSourceReadRecovery abortSourceRead( + String originalCompactJwt, UUID intakeRequestId, DraftCommitBinding selected) { + return abortSourceRead( + findScope(originalCompactJwt, intakeRequestId, selected) + .orElseThrow( + () -> new IllegalArgumentException("Original source-read reservation absent"))); + } + + private java.util.Optional findScope( + String originalCompactJwt, UUID intakeRequestId, DraftCommitBinding selected) { + requirePeer(); + outsideSql(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( + intakeRequestId); + Objects.requireNonNull(selected); + if (originalCompactJwt == null + || originalCompactJwt.isEmpty() + || originalCompactJwt.length() > 16384 + || !java.nio.charset.StandardCharsets.US_ASCII.newEncoder().canEncode(originalCompactJwt)) + throw Status.UNAUTHENTICATED.asRuntimeException(); + var hash = + AccountControlUiIssuanceRepository.hash( + originalCompactJwt.getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + return Objects.requireNonNull( + transaction.execute( + ignored -> repository.findSourceReadScope(intakeRequestId, selected, namespace, hash))); + } + + private void requireScope(GameLogicIntakeSourceReadScope scope) { + if (scope == null || !namespace.equals(scope.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Independent Account intake phase required") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java new file mode 100644 index 0000000000..f8cfa11aa8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; + +/** Immutable Account receipt; transport correlations never enter mutation identity. */ +public record AccountGameLogicIntakeSettlement(GameLogicGameplayRuleIntakeTerminal terminal) { + public static final String SCHEMA = AccountGameLogicIntakeSettlementEvidence.SCHEMA; + + public AccountGameLogicIntakeSettlement { + Objects.requireNonNull(terminal); + } + + public byte[] canonicalBytes() { + return new AccountGameLogicIntakeSettlementEvidence(terminal).canonicalBytes(); + } + + public String digest() { + return new AccountGameLogicIntakeSettlementEvidence(terminal).digest(); + } + + public static AccountGameLogicIntakeSettlement fromStored(byte[] bytes) { + return new AccountGameLogicIntakeSettlement( + AccountGameLogicIntakeSettlementEvidence.fromStored(bytes).terminal()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java new file mode 100644 index 0000000000..d1d8f738d2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementProtoCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered GD-only transport; Account alone reads GL terminal and owns settlement. */ +public final class AccountGameLogicIntakeSettlementGrpcService + extends AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceImplBase { + private final AccountGameLogicIntakeSettlementService owner; + private final String namespace; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected owner service is an intentionally shared transport collaborator.") + public AccountGameLogicIntakeSettlementGrpcService( + AccountGameLogicIntakeSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + @Override + public void settleGameLogicIntake( + SettleGameLogicIntakeRequest wire, StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountGameLogicIntakeSettlementReadEvidence.Request request; + try { + request = AccountGameLogicIntakeSettlementProtoCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final SettleGameLogicIntakeResponse response; + try { + var receipt = owner.settle(request.binding()); + response = + AccountGameLogicIntakeSettlementProtoCodec.toResponse( + new AccountGameLogicIntakeSettlementReadEvidence( + request, new AccountGameLogicIntakeSettlementEvidence(receipt.terminal()))); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account intake settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java new file mode 100644 index 0000000000..19c2828334 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered GD-only producer: genuine GL terminal read completes before Account SQL. */ +public final class AccountGameLogicIntakeSettlementService { + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final GameLogicIntakeTerminalReadClient terminals; + private final TransactionTemplate transaction; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected repository is an intentionally shared service collaborator.") + public AccountGameLogicIntakeSettlementService( + AccountGameLogicIntakeAuthorizationRepository repository, + GameLogicIntakeTerminalReadClient terminals, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.terminals = Objects.requireNonNull(terminals); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public AccountGameLogicIntakeSettlement settle(GameLogicIntakeAuthorizationBinding original) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + Objects.requireNonNull(original); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Terminal read must precede Account SQL") + .asRuntimeException(); + // The retained V97 origin is checked even when no settlement exists, before remote dispatch. + var prior = transaction.execute(ignored -> repository.findSettlement(original, namespace)); + if (prior != null && prior.isPresent()) return prior.orElseThrow(); + var request = GameLogicIntakeTerminalReadEvidence.Request.create(namespace, original); + var evidence = terminals.read(request); + if (evidence == null || !request.equals(evidence.request()) || evidence.terminal().isEmpty()) + throw Status.FAILED_PRECONDITION + .withDescription("Exact definitive GL terminal required") + .asRuntimeException(); + var terminal = evidence.terminal().orElseThrow(); + if (!namespace.equals(terminal.operation().targetNamespace()) + || !Arrays.equals(original.canonicalBytes(), terminal.authorizationBytes())) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + return transaction.execute( + ignored -> repository.settle(new AccountGameLogicIntakeSettlement(terminal))); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java new file mode 100644 index 0000000000..8912df9cdc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Standalone GD-only confirmation; no runtime registration. */ +public final class AccountGameLogicIntakeSourceReadGrpcService + extends AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceImplBase { + private final AccountGameLogicIntakeSourceReadService owner; + private final String namespace; + + public AccountGameLogicIntakeSourceReadGrpcService( + AccountGameLogicIntakeSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readSourceScope( + GameLogicIntakeSourcePermissionRequest request, + StreamObserver observer) { + read(request, observer, true); + } + + @Override + public void readFinalizedIntake( + GameLogicIntakeSourcePermissionRequest request, + StreamObserver observer) { + read(request, observer, false); + } + + private void read( + GameLogicIntakeSourcePermissionRequest request, + StreamObserver observer, + boolean preliminary) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request decoded; + try { + decoded = GameLogicIntakeSourceReadProtoCodec.fromRequest(request); + if (preliminary != (decoded.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary)) + throw new IllegalArgumentException("Wrong proof method"); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + try { + if (decoded.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary proof) { + var result = + owner.readSourceScope(proof.scope(), decoded.intendedReader(), decoded.purpose()); + if (!proof.scope().equals(result)) + throw new IllegalStateException("Changed Account source scope"); + } else { + var proof = (GameplayRuleSourceReadEvidence.Finalized) decoded.proof(); + var result = + owner.readFinalizedIntake( + proof.authorization(), decoded.intendedReader(), decoded.purpose()); + if (!java.util.Arrays.equals( + proof.authorization().canonicalBytes(), result.canonicalBytes())) + throw new IllegalStateException("Changed Account final authorization"); + } + observer.onNext(GameLogicIntakeSourceReadProtoCodec.toResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (IllegalArgumentException | IllegalStateException failure) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java new file mode 100644 index 0000000000..38f6278473 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; + +/** Original two-phase result only; recovery does not grant a new read or mutation. */ +public record AccountGameLogicIntakeSourceReadRecovery( + GameLogicIntakeSourceReadScope scope, + State state, + Optional authorization) { + public enum State { + RESERVED, + FINALIZED, + ABORTED + } + + public AccountGameLogicIntakeSourceReadRecovery { + Objects.requireNonNull(scope); + Objects.requireNonNull(state); + Objects.requireNonNull(authorization); + if ((state == State.FINALIZED) != authorization.isPresent()) + throw new IllegalArgumentException("Exact phase result required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java new file mode 100644 index 0000000000..5db667b9ee --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.time.Clock; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered GD-only readback of existing source-read authority; never issues a grant. */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner collaborators.") +public final class AccountGameLogicIntakeSourceReadService { + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final AccountControlUiCoordination registry; + private final TransactionTemplate transaction; + private final Clock clock; + private final String namespace; + + public AccountGameLogicIntakeSourceReadService( + AccountGameLogicIntakeAuthorizationRepository repository, + AccountControlUiCoordination registry, + PlatformTransactionManager transactions, + Clock clock, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.registry = Objects.requireNonNull(registry); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public GameLogicIntakeSourceReadScope readSourceScope( + GameLogicIntakeSourceReadScope scope, String intendedReader, String purpose) { + requirePeer(); + requireReader(intendedReader, purpose, "account-service"); + Objects.requireNonNull(scope); + if (!namespace.equals(scope.targetNamespace()) + || !intendedReader.equals(scope.intendedReader()) + || !purpose.equals(scope.purpose())) throw Status.PERMISSION_DENIED.asRuntimeException(); + outsideSql(); + var current = + Objects.requireNonNull( + transaction.execute(ignored -> repository.sourceReadCurrentness(scope))); + var active = registry.readActive(current.tokenHash()); + if (!current.registryDigest().equals(DraftAuthorizationFenceBinding.digest(active))) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + return transaction.execute( + ignored -> { + repository.readSourceScope(scope, current, clock.instant()); + return scope; + }); + } + + public GameLogicIntakeAuthorizationBinding readFinalizedIntake( + GameLogicIntakeAuthorizationBinding authorization, String intendedReader, String purpose) { + requirePeer(); + requireReader(intendedReader, purpose, "game-logic-service"); + Objects.requireNonNull(authorization); + outsideSql(); + return transaction.execute( + ignored -> { + repository.readFinalizedSourceScope(authorization, namespace); + return authorization; + }); + } + + private void requireReader(String reader, String purpose, String service) { + if (!("spiffe://firemud/ns/" + namespace + "/sa/" + service).equals(reader) + || !GameLogicIntakeSourceReadScope.PURPOSE.equals(purpose)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..3e5861746f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,1028 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real creator issuance/currentness, Account transactions, intake/reservation and source guards. GD + * source transport and the original author's terminal are explicit upstream fixtures, not composed + * production or mTLS proof. The namespace case supplies a controlled GL terminal to the actual + * Account settlement owner; it does not prove authenticated GL production or runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountGameLogicIntakeAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("intake-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "intake-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void retainedOriginNamespaceFencesHeldTerminalDispatchAndSettlementReplay() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var source = source(selected); + var sources = mock(GameplayRuleSourceReadClient.class); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(sources) + .read(any()); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var authorizer = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, sources, f.manager, "test"); + var order = + asGameDesign( + () -> + authorizer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); + var held = new AccountGameLogicIntakeAuthorizationReadService(repository, f.manager, "test"); + asPeer( + "test", + "game-logic-service", + () -> { + held.requireHeld( + GameLogicIntakeAuthorizationReadEvidence.Request.create("test", order)); + return null; + }); + var wrongHeld = + new AccountGameLogicIntakeAuthorizationReadService(repository, f.manager, "other"); + var terminals = mock(GameLogicIntakeTerminalReadClient.class); + var wrongSettlement = + new AccountGameLogicIntakeSettlementService(repository, terminals, f.manager, "other"); + var before = retainedIntakeRows(f.dsl); + assertThatThrownBy( + () -> + asPeer( + "other", + "game-logic-service", + () -> { + wrongHeld.requireHeld( + GameLogicIntakeAuthorizationReadEvidence.Request.create( + "other", order)); + return null; + })) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThatThrownBy( + () -> asPeer("other", "game-design-service", () -> wrongSettlement.settle(order))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Changed original source namespace"); + verifyNoInteractions(terminals); + var wrongTerminal = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("other", order)); + assertThatThrownBy( + () -> + f.tx( + () -> repository.settle(new AccountGameLogicIntakeSettlement(wrongTerminal)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Changed original source namespace"); + String genesis = + GameplayRuleManifest.tree(source.snapshotJson()).path("genesisReceiptId").textValue(); + var changedOrder = + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding( + order.operationId(), + order.fenceId(), + order.intakeRequestId(), + order.actorAccountId(), + new GameplayRuleSelectedSource( + source.snapshotJson().replace(genesis, UUID.randomUUID().toString())), + order.sources()); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeld(changedOrder, "test"); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Original intake order absent or changed"); + assertThat(retainedIntakeRows(f.dsl)).isEqualTo(before); + + // Controlled terminal input; the Account transaction, SQL guard and retained receipt are + // real. + var terminal = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", order)); + doAnswer( + call -> + new GameLogicIntakeTerminalReadEvidence( + call.getArgument(0), java.util.Optional.of(terminal))) + .when(terminals) + .read(any()); + var settlement = + new AccountGameLogicIntakeSettlementService(repository, terminals, f.manager, "test"); + var receipt = asGameDesign(() -> settlement.settle(order)); + assertThat(receipt.canonicalBytes()) + .containsExactly(new AccountGameLogicIntakeSettlement(terminal).canonicalBytes()); + var settled = retainedIntakeRows(f.dsl); + clearInvocations(terminals); + assertThat(asGameDesign(() -> settlement.settle(order)).canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + assertThatThrownBy( + () -> asPeer("other", "game-design-service", () -> wrongSettlement.settle(order))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Changed original source namespace"); + verifyNoInteractions(terminals); + assertThat(retainedIntakeRows(f.dsl)).isEqualTo(settled); + } + } + + /** + * Every retained column and physical row version survives rejected selectors and exact replay. + */ + private static Map> retainedIntakeRows(org.jooq.DSLContext dsl) { + Map> rows = new java.util.TreeMap<>(); + for (String table : + List.of( + "account_game_logic_intake_source_read_reservations", + "account_game_logic_intake_source_read_sources", + "account_game_logic_intake_source_read_aborts", + "account_game_logic_intake_authorizations", + "account_game_logic_intake_sources", + "account_game_logic_intake_settlements")) { + rows.put( + table, + dsl.fetch( + "SELECT row_to_json(t)::text || ':' || t.xmin::text AS retained FROM " + + table + + " t ORDER BY row_to_json(t)::text") + .getValues("retained", String.class)); + } + return rows; + } + + @Test + void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisclosure() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + var source = source(selected); + var gd = mock(GameplayRuleSourceReadClient.class); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(gd) + .read(any()); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var requestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(gd); + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_game_logic_intake_authorizations"))) + .isZero(); + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + var order = + asGameDesign( + () -> service.authorize(issued.compact(), requestId, selected, issued.environment())); + assertThat(order.source()).isEqualTo(source); + assertThat(order.sources()).hasSize(captured.sources().size()); + assertThat( + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + String genesis = + GameplayRuleManifest.tree(source.snapshotJson()).path("genesisReceiptId").textValue(); + var substituted = + new GameplayRuleSelectedSource( + source.snapshotJson().replace(genesis, UUID.randomUUID().toString())); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), substituted)) + .when(gd) + .read(any()); + clearInvocations(gd); + assertThat( + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + verifyNoInteractions(gd); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(gd) + .read(any()); + + UUID rolledBackRequest = UUID.randomUUID(); + assertThatThrownBy( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + f.fences.lockProducerSourcesNowait(current.source().sources()); + repository.reserveSourceRead( + rolledBackRequest, + selected, + current, + "test", + () -> + f.fences.requireGameLogicIntakeAdmission( + current.source().sources(), selected)); + throw new IllegalStateException("rollback before owner commit"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchOne( + "SELECT 1 FROM account_game_logic_intake_source_read_reservations WHERE intake_request_id = ?", + rolledBackRequest)) + .isNull(); + f.tx( + () -> { + repository.readHeld(order, "test"); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(order.sources()); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("intake"); + + // Only the distinct intake is pending; original Draft settlement is already COMMITTED. + assertThat(f.tx(() -> f.fences.readSettlement(original))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) + .hasStackTraceContaining("Distinct Game Logic intake remains pending"); + + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), order.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceAbortPermitted(change))).isFalse(); + f.tx( + () -> { + repository.readHeld(order, "test"); + return null; + }); + + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE account_game_logic_intake_authorizations SET source_digest = ? WHERE operation_id = ?", + "sha256:" + "0".repeat(64), + order.operationId()); + return null; + })) + .hasStackTraceContaining("immutable"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + "invalid-credential", + UUID.randomUUID(), + selected, + issued.environment()))) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void lostFirstResponseRecoversByOriginalRequestAfterExpiryAndAbortReleasesParticipation() + throws Exception { + var offsetSeconds = new java.util.concurrent.atomic.AtomicLong(); + var clock = + new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return Instant.now().plusSeconds(offsetSeconds.get()); + } + }; + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var gd = mock(GameplayRuleSourceReadClient.class); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var requestId = UUID.randomUUID(); + doAnswer( + call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = (GameplayRuleSourceReadEvidence.Request) call.getArgument(0); + var scope = ((GameplayRuleSourceReadEvidence.Preliminary) request.proof()).scope(); + var retainedScope = + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT scope_bytes FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + scope.operationId()), + "Reserved source scope row required"); + assertThat(retainedScope.get("scope_bytes", byte[].class)) + .isEqualTo(scope.canonicalBytes()); + throw io.grpc.Status.UNAVAILABLE + .withDescription("test-only lost source response") + .asRuntimeException(); + }) + .when(gd) + .read(any()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var recovered = asGameDesign(() -> service.recover(issued.compact(), requestId, selected)); + assertThat(recovered.state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); + assertThat( + asGameDesign( + () -> + service.reserveSourceRead( + issued.compact(), requestId, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(recovered.scope().canonicalBytes()); + doAnswer( + call -> { + throw io.grpc.Status.PERMISSION_DENIED.asRuntimeException(); + }) + .when(gd) + .read(any()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("PERMISSION_DENIED"); + assertThat(asGameDesign(() -> service.recover(issued.compact(), requestId, selected)).scope()) + .isEqualTo(recovered.scope()); + var originalSources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())).sources(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(originalSources); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("intake"); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) + .hasStackTraceContaining("Preliminary Game Logic source read remains pending"); + assertThatThrownBy( + () -> + asGameDesign( + () -> service.recover("different-original-credential", requestId, selected))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + assertThatThrownBy( + () -> + asGameDesign( + () -> service.recover(issued.compact(), requestId, selected(f.tenant)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + clearInvocations(gd); + offsetSeconds.set(600); + assertThat(asGameDesign(() -> service.recover(issued.compact(), requestId, selected)).scope()) + .isEqualTo(recovered.scope()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(gd); + var aborted = + asGameDesign(() -> service.abortSourceRead(issued.compact(), requestId, selected)); + assertThat(aborted.state()).isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); + assertThat(asGameDesign(() -> service.abortSourceRead(recovered.scope()))).isEqualTo(aborted); + f.tx( + () -> { + f.fences.requireDisclosurePreparation(originalSources); + return null; + }); + f.tx( + () -> { + f.changeRoleToAdmin(); + return null; + }); + assertThat( + f.dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + recovered.scope().operationId())) + .isNull(); + } + } + + @Test + void abortWhileSourceReadIsInFlightExcludesLateFinalizationAndExactFinalRetrySurvivesExpiry() + throws Exception { + var offsetSeconds = new java.util.concurrent.atomic.AtomicLong(); + var clock = + new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return Instant.now().plusSeconds(offsetSeconds.get()); + } + }; + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var source = source(selected); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var gd = mock(GameplayRuleSourceReadClient.class); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var arrived = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + doAnswer( + call -> { + arrived.countDown(); + if (!release.await(20, java.util.concurrent.TimeUnit.SECONDS)) + throw new IllegalStateException("Source response barrier timed out"); + return new GameplayRuleSourceReadEvidence(call.getArgument(0), source); + }) + .when(gd) + .read(any()); + var requestId = UUID.randomUUID(); + var inFlight = + java.util.concurrent.CompletableFuture.supplyAsync( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))); + assertThat(arrived.await(20, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var aborted = + asGameDesign(() -> service.abortSourceRead(issued.compact(), requestId, selected)); + release.countDown(); + assertThatThrownBy(() -> inFlight.get(20, java.util.concurrent.TimeUnit.SECONDS)) + .hasRootCauseMessage("Original source-read scope aborted"); + assertThat(aborted.state()).isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); + assertThat( + f.dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + aborted.scope().operationId())) + .isNull(); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(gd) + .read(any()); + var finalRequest = UUID.randomUUID(); + var order = + asGameDesign( + () -> + service.authorize( + issued.compact(), finalRequest, selected, issued.environment())); + var recovery = asGameDesign(() -> service.recover(issued.compact(), finalRequest, selected)); + assertThat(order.operationId()).isEqualTo(recovery.scope().operationId()); + assertThat(order.fenceId()).isEqualTo(recovery.scope().fenceId()); + var readOwner = + new AccountGameLogicIntakeSourceReadService( + repository, + mock(AccountControlUiCoordination.class), + f.manager, + Clock.systemUTC(), + "test"); + assertThat( + asGameDesign( + () -> + readOwner.readFinalizedIntake( + order, + "spiffe://firemud/ns/test/sa/game-logic-service", + GameLogicIntakeSourceReadScope.PURPOSE)) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_aborts (operation_id) VALUES (?)", + order.operationId()); + return null; + })) + .hasStackTraceContaining("Finalized intake cannot be preliminarily aborted"); + assertThat(asGameDesign(() -> service.abortSourceRead(recovery.scope())).state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED); + offsetSeconds.set(600); + clearInvocations(gd); + assertThat( + asGameDesign( + () -> + service.authorize( + issued.compact(), finalRequest, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + verifyNoInteractions(gd); + } + } + + private static void settleOriginal( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, DraftCommitBinding selected) { + var f = issued.sources(); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + } + + @Test + void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannotFinalize() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var registry = mock(AccountControlUiCoordination.class); + doAnswer( + call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var retainedIssuer = + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT active_registry FROM account_control_ui_issuance_operations WHERE token_hash = ?", + call.getArgument(0, String.class)), + "Original active registry row required"); + return retainedIssuer.get("active_registry", byte[].class); + }) + .when(registry) + .readActive(any()); + var owner = + new AccountGameLogicIntakeSourceReadService( + repository, registry, f.manager, Clock.systemUTC(), "test"); + var gd = mock(GameplayRuleSourceReadClient.class); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var request = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + service.reserveSourceRead( + issued.compact(), request, selected, issued.environment())); + assertThat( + asGameDesign( + () -> owner.readSourceScope(scope, scope.intendedReader(), scope.purpose())) + .canonicalBytes()) + .isEqualTo(scope.canonicalBytes()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + owner.readSourceScope( + scope, + "spiffe://firemud/ns/test/sa/game-logic-service", + scope.purpose()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + asGameDesign( + () -> owner.readSourceScope(scope, scope.intendedReader(), "PUBLICATION"))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var changed = + new GameLogicIntakeSourceReadScope( + scope.targetNamespace(), + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + UUID.randomUUID(), + scope.selected(), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + owner.readSourceScope( + changed, changed.intendedReader(), changed.purpose()))) + .isInstanceOf(IllegalArgumentException.class); + var expiredReader = + new AccountGameLogicIntakeSourceReadService( + repository, + registry, + f.manager, + Clock.offset(Clock.systemUTC(), java.time.Duration.ofMinutes(10)), + "test"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + expiredReader.readSourceScope( + scope, scope.intendedReader(), scope.purpose()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("current held"); + // Direct SQL cannot establish a changed purpose even with exact committed issuance bytes. + var changedPurpose = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(changedPurpose, GameLogicIntakeSourceReadScope.SCHEMA); + DraftAuthorizationFenceBinding.frame(changedPurpose, scope.targetNamespace()); + var badOperation = UUID.randomUUID(); + var badFence = UUID.randomUUID(); + var badRequest = UUID.randomUUID(); + for (var id : List.of(badOperation, badFence, badRequest, scope.actorAccountId())) + DraftAuthorizationFenceBinding.frame(changedPurpose, id.toString()); + DraftAuthorizationFenceBinding.frame(changedPurpose, selected.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(changedPurpose, selected.digest()); + DraftAuthorizationFenceBinding.frame(changedPurpose, scope.intendedReader()); + DraftAuthorizationFenceBinding.frame(changedPurpose, "PUBLICATION"); + var malformed = changedPurpose.toByteArray(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "SELECT ?, ?, ?, actor_account_uuid, tenant_uuid, version_uuid, ?, ?, issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints " + + "FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + badOperation, + badFence, + badRequest, + malformed, + DraftAuthorizationFenceBinding.digest(malformed), + scope.operationId()); + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_sources SELECT ?, source_key, source_evidence FROM account_game_logic_intake_source_read_sources WHERE operation_id = ?", + badOperation, + scope.operationId()); + return null; + })) + .hasStackTraceContaining("Invalid preliminary purpose"); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + badOperation)) + .isNull(); + doAnswer( + call -> { + var sourceRequest = (GameplayRuleSourceReadEvidence.Request) call.getArgument(0); + assertThat( + ((GameplayRuleSourceReadEvidence.Preliminary) sourceRequest.proof()) + .scope()) + .isEqualTo(scope); + owner.readSourceScope(scope, scope.intendedReader(), scope.purpose()); + f.boundary.set( + AccountControlUiOwnerSourcesFixture.testBoundary( + "changed-current-environment")); + return new GameplayRuleSourceReadEvidence(sourceRequest, source(selected)); + }) + .when(gd) + .read(any()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorizeWithEnvironmentCapture( + issued.compact(), + request, + selected, + f.terms::captureCurrentEnvironmentBoundary))) + .isInstanceOf(RuntimeException.class); + assertThat(asGameDesign(() -> service.recover(issued.compact(), request, selected)).state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + scope.operationId())) + .isNull(); + assertThat( + asGameDesign(() -> service.abortSourceRead(issued.compact(), request, selected)) + .state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); + } + } + + private static DraftCommitBinding selected(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding selected) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + Map> families = + new EnumMap<>(GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + selected.canonicalJson(), + "sourceBindingDigest", + selected.digest(), + "revisionOrder", + "0", + "revisionId", + selected.revisions().getFirst().revisionId().toString()))))); + } + + private static T asGameDesign(java.util.function.Supplier action) { + return asPeer("test", "game-design-service", action); + } + + private static T asPeer( + String namespace, String service, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java new file mode 100644 index 0000000000..60ba413179 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java @@ -0,0 +1,410 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationGrpcCodec; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver boundary tests; no PostgreSQL or genuine authoring provenance is implied. */ +class AccountGameLogicIntakeAuthorizationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String CREDENTIAL = "original.creator.credential"; + + private final AccountGameLogicIntakeAuthorizationService owner = + mock(AccountGameLogicIntakeAuthorizationService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountGameLogicIntakeAuthorizationGrpcService receiver = + new AccountGameLogicIntakeAuthorizationGrpcService(owner, terms, NAMESPACE); + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactPeerAndCredentialBeforeDecodingOrOwnerCapture() { + assertThat(invokeAuthorize(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "game-logic-service", "account-service")) + assertThat(peer(NAMESPACE, workload, () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + peer( + NAMESPACE, + "game-design-service", + () -> invokeAuthorize(GameLogicIntakeAuthorizationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat( + authorized( + () -> + invokeAuthorize( + GameLogicIntakeAuthorizationRequest.newBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + authorized( + () -> + invokeAuthorize(request().toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesPeerBeforeReadingMethodLocalCredential() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountGameLogicIntakeAuthorizationCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 255}); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + } + + @Test + void capturesEnvironmentOnlyThroughSupplierAndEchoesExactSelectionWithoutCredential() { + var safeRequest = request(); + var decoded = GameLogicIntakeAuthorizationGrpcCodec.fromRequest(safeRequest); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + var binding = authorization(decoded); + var captures = new AtomicInteger(); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + captures.incrementAndGet(); + return captured; + }); + when(owner.authorizeWithEnvironmentCapture( + eq(CREDENTIAL), eq(decoded.intakeRequestId()), eq(decoded.selected()), any())) + .thenAnswer( + call -> { + Supplier capture = call.getArgument(3); + assertThat(capture.get()).isSameAs(captured); + return binding; + }); + + var result = authorized(() -> invokeAuthorize(safeRequest)); + assertThat(result.error()).isNull(); + assertThat(captures).hasValue(1); + var response = GameLogicIntakeAuthorizationGrpcCodec.fromResponse(decoded, result.response()); + assertThat(response.authorization().orElseThrow().canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + assertThat(safeRequest.toString()).doesNotContain(CREDENTIAL); + } + + @Test + void explicitRecoverAndAbortUseTheSameProtectedRequestWithoutEnvironmentCapture() { + var wire = request(); + var decoded = GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wire); + var selected = decoded.selected(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + decoded.intakeRequestId(), + UUID.randomUUID(), + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var reserved = + new AccountGameLogicIntakeSourceReadRecovery( + scope, AccountGameLogicIntakeSourceReadRecovery.State.RESERVED, Optional.empty()); + var aborted = + new AccountGameLogicIntakeSourceReadRecovery( + scope, AccountGameLogicIntakeSourceReadRecovery.State.ABORTED, Optional.empty()); + when(owner.recover(CREDENTIAL, decoded.intakeRequestId(), selected)).thenReturn(reserved); + when(owner.abortSourceRead(CREDENTIAL, decoded.intakeRequestId(), selected)) + .thenReturn(aborted); + + var recovered = authorized(() -> invoke(wire, Operation.RECOVER)); + var stopped = authorized(() -> invoke(wire, Operation.ABORT)); + assertThat(recovered.error()).isNull(); + assertThat(stopped.error()).isNull(); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(decoded, recovered.response()) + .outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(decoded, stopped.response()) + .outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); + org.mockito.Mockito.verify(owner).recover(CREDENTIAL, decoded.intakeRequestId(), selected); + org.mockito.Mockito.verify(owner) + .abortSourceRead(CREDENTIAL, decoded.intakeRequestId(), selected); + verifyNoInteractions(terms); + } + + @Test + void rejectsAmbientSqlBeforeAnyAccountOwnerAccess() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat(authorized(() -> invokeAuthorize(request())).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(owner, terms); + } + + @Test + void reportsOwnerFailuresBySanitizedStatusAndNeverEchoesCredential() { + when(owner.authorizeWithEnvironmentCapture(eq(CREDENTIAL), any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invokeAuthorize(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result(GameLogicIntakeAuthorizationResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invokeAuthorize(GameLogicIntakeAuthorizationRequest request) { + return invoke(request, Operation.AUTHORIZE); + } + + private Result invoke(GameLogicIntakeAuthorizationRequest request, Operation operation) { + var response = new AtomicReference(); + var error = new AtomicReference(); + var observer = + new io.grpc.stub.StreamObserver() { + @Override + public void onNext(GameLogicIntakeAuthorizationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }; + switch (operation) { + case AUTHORIZE -> receiver.authorizeIntake(request, observer); + case RECOVER -> receiver.recoverIntake(request, observer); + case ABORT -> receiver.abortIntake(request, observer); + } + return new Result(response.get(), error.get()); + } + + private enum Operation { + AUTHORIZE, + RECOVER, + ABORT + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition< + GameLogicIntakeAuthorizationRequest, GameLogicIntakeAuthorizationResponse>) + receiver.bindService().getMethods().stream() + .filter( + candidate -> + candidate + .getMethodDescriptor() + .getFullMethodName() + .equals( + net.firedevops.firemud.account.v1 + .AccountGameLogicIntakeAuthorizationServiceGrpc + .getAuthorizeIntakeMethod() + .getFullMethodName())) + .findFirst() + .orElseThrow(); + io.grpc.ServerCall + call = mock(io.grpc.ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method.getMethodDescriptor()); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + private static T authorized(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer(NAMESPACE, "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static GameLogicIntakeAuthorizationRequest request() { + var safe = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selected()); + return GameLogicIntakeAuthorizationGrpcCodec.toRequest(safe); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeAuthorizationEvidence.Request request) { + var selected = request.selected(); + var actor = UUID.randomUUID(); + var source = selectedSource(selected); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + var revision = binding.revisions().getFirst(); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + revision.revisionOrder(), + "revisionId", + revision.revisionId().toString()))))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java new file mode 100644 index 0000000000..7f34ac6a63 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class AccountGameLogicIntakeAuthorizationReadGrpcServiceTest { + @Test + void callerAuthenticationPrecedesBindingParsingAndRepositoryAccess() { + var owner = mock(AccountGameLogicIntakeAuthorizationReadService.class); + var service = new AccountGameLogicIntakeAuthorizationReadGrpcService(owner, "test"); + var malformed = + ReadHeldGameLogicIntakeAuthorizationRequest.newBuilder().setSchemaVersion(-1).build(); + var missing = new Collector(); + service.readHeldGameLogicIntakeAuthorization(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + for (var caller : + new String[] {"world-management-service", "account-service", "game-design-service"}) { + var result = new Collector(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + caller).orElseThrow()) + .run(() -> service.readHeldGameLogicIntakeAuthorization(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var allowedMalformed = new Collector(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()) + .run(() -> service.readHeldGameLogicIntakeAuthorization(malformed, allowedMalformed)); + assertThat(allowedMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + + public void onNext(ReadHeldGameLogicIntakeAuthorizationResponse value) { + throw new AssertionError("No positive result"); + } + + public void onError(Throwable value) { + error = Status.fromThrowable(value).getCode(); + } + + public void onCompleted() { + throw new AssertionError("No successful read"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java new file mode 100644 index 0000000000..27d2bcd053 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java @@ -0,0 +1,315 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameLogicIntakeAuthorizationRecoveryTest { + private static final String CREDENTIAL = "unchanged.creator.credential"; + private static final String NAMESPACE = "test"; + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactFinalizedRetryRecoversBeforeCapturingMutableEnvironmentAuthority() { + var selected = selected(); + var intakeRequestId = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + intakeRequestId, + actor, + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var authorization = authorization(scope, actor); + var actors = mock(AccountControlUiActorService.class); + var fences = + mock( + net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository + .class); + var repository = mock(AccountGameLogicIntakeAuthorizationRepository.class); + var sourceClient = mock(GameplayRuleSourceReadClient.class); + when(repository.findSourceReadScope( + eq(intakeRequestId), eq(selected), eq(NAMESPACE), anyString())) + .thenReturn(Optional.of(scope)); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountGameLogicIntakeSourceReadRecovery( + scope, + AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED, + Optional.of(authorization))); + + var service = + new AccountGameLogicIntakeAuthorizationService( + actors, fences, repository, sourceClient, new NoopTransactionManager(), NAMESPACE); + var captures = new AtomicInteger(); + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + var recovered = + service.authorizeWithEnvironmentCapture( + CREDENTIAL, + intakeRequestId, + selected, + () -> { + captures.incrementAndGet(); + throw new IllegalStateException("mutable environment must not be read on retry"); + }); + assertThat(recovered.canonicalBytes()).containsExactly(authorization.canonicalBytes()); + } finally { + context.detach(prior); + } + assertThat(captures).hasValue(0); + verify(repository) + .findSourceReadScope(eq(intakeRequestId), eq(selected), eq(NAMESPACE), anyString()); + verify(repository).recoverSourceRead(scope); + verifyNoInteractions(actors, fences, sourceClient); + } + + @Test + void requiresFreshAuthorityAfterRemoteSourceReadBeforeFinalization() { + var selected = selected(); + var intakeRequestId = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + intakeRequestId, + actor, + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var authorization = authorization(scope, actor); + var actors = mock(AccountControlUiActorService.class); + var fences = mock(DraftAuthorizationFenceRepository.class); + var repository = mock(AccountGameLogicIntakeAuthorizationRepository.class); + var sourceClient = mock(GameplayRuleSourceReadClient.class); + var initialEnvironment = mock(CapturedEnvironmentBoundary.class); + var events = new ArrayList(); + var current = mock(AccountControlUiActorService.Current.class); + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(current.source()).thenReturn(snapshot); + when(snapshot.sources()).thenReturn(List.of()); + when(repository.findSourceReadScope( + eq(intakeRequestId), eq(selected), eq(NAMESPACE), anyString())) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(intakeRequestId), eq(selected), eq(current), eq(NAMESPACE), any(Runnable.class))) + .thenReturn(scope); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountGameLogicIntakeSourceReadRecovery( + scope, AccountGameLogicIntakeSourceReadRecovery.State.RESERVED, Optional.empty())); + when(sourceClient.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + call -> { + events.add("source-read"); + return new GameplayRuleSourceReadEvidence( + call.getArgument(0), authorization.source()); + }); + var actorCalls = new AtomicInteger(); + doAnswer( + call -> { + events.add("actor-" + actorCalls.incrementAndGet()); + @SuppressWarnings("unchecked") + Function action = + (Function) call.getArgument(3); + return action.apply(current); + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + + var service = + new AccountGameLogicIntakeAuthorizationService( + actors, fences, repository, sourceClient, new NoopTransactionManager(), NAMESPACE); + var environmentCaptures = new AtomicInteger(); + var currentnessUnavailable = new IllegalStateException("fresh authority unavailable"); + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + assertThatThrownBy( + () -> + service.authorizeWithEnvironmentCapture( + CREDENTIAL, + intakeRequestId, + selected, + () -> { + if (environmentCaptures.incrementAndGet() == 1) { + events.add("capture-reservation"); + return initialEnvironment; + } + events.add("capture-finalization"); + throw currentnessUnavailable; + })) + .isSameAs(currentnessUnavailable); + } finally { + context.detach(prior); + } + + assertThat(environmentCaptures).hasValue(2); + assertThat(actorCalls).hasValue(1); + assertThat(events) + .containsExactly("capture-reservation", "actor-1", "source-read", "capture-finalization"); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeSourceReadScope scope, UUID actor) { + var selected = scope.selected(); + var source = selectedSource(selected); + return new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + var revision = binding.revisions().getFirst(); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + revision.revisionOrder(), + "revisionId", + revision.revisionId().toString()))))); + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..a2ecb6a2b0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -0,0 +1,313 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementProtoCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level transport proofs; durable settlement belongs to the owner service. */ +class AccountGameLogicIntakeSettlementGrpcServiceTest { + private final AccountGameLogicIntakeSettlementService owner = + mock(AccountGameLogicIntakeSettlementService.class); + private final AccountGameLogicIntakeSettlementGrpcService receiver = + new AccountGameLogicIntakeSettlementGrpcService(owner, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeDecodeAndDeniesEveryOtherWorkloadAndNamespace() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (var workload : + List.of( + "account-service", + "game-logic-service", + "world-management-service", + "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(authorized(() -> invoke(SettleGameLogicIntakeRequest.getDefaultInstance())).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void deniesAmbientSqlAndChangedTargetBeforeOwner() { + var request = + AccountGameLogicIntakeSettlementProtoCodec.toRequest( + evidence("test", 1, Outcome.ABORTED).request()); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void returnsExactRetainedAndAbortedReceiptForNewCorrelationRetryWithoutChangingBytes() { + for (var outcome : Outcome.values()) { + var evidence = evidence("test", 1, outcome); + var receipt = new AccountGameLogicIntakeSettlement(evidence.receipt().terminal()); + when(owner.settle(any())).thenReturn(receipt); + var first = + authorized( + () -> + invoke(AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()))); + assertThat(first.error()).isNull(); + assertThat( + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), first.response()) + .receipt() + .canonicalBytes()) + .isEqualTo(receipt.canonicalBytes()); + var retry = + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "test", evidence.request().binding()); + var replay = + authorized(() -> invoke(AccountGameLogicIntakeSettlementProtoCodec.toRequest(retry))); + assertThat(replay.error()).isNull(); + assertThat(replay.response().getOriginalSettlementReceipt()) + .isEqualTo(first.response().getOriginalSettlementReceipt()); + assertThat(replay.response().getRequest()).isNotEqualTo(first.response().getRequest()); + assertThat(receipt.canonicalBytes()).isEqualTo(evidence.receipt().canonicalBytes()); + assertThat(AccountGameLogicIntakeSettlement.fromStored(receipt.canonicalBytes()).digest()) + .isEqualTo(receipt.digest()); + } + } + + @Test + void substitutedOwnerReceiptAndOwnerFailureDenyWithoutLeakingDiagnostics() { + var evidence = evidence("test", 1, Outcome.RETAINED); + var request = AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()); + when(owner.settle(any())) + .thenReturn( + new AccountGameLogicIntakeSettlement( + evidence("test", 1, Outcome.RETAINED).receipt().terminal())); + assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.UNAVAILABLE); + when(owner.settle(any())) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("private-owner-evidence") + .asRuntimeException()); + var failed = authorized(() -> invoke(request)); + assertThat(failed.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(failed.error().toString()).doesNotContain("private-owner-evidence"); + } + + private record Result(SettleGameLogicIntakeResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(SettleGameLogicIntakeRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.settleGameLogicIntake( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(SettleGameLogicIntakeResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static T authorized(java.util.function.Supplier action) { + return peer("test", "game-design-service", action); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private enum Outcome { + RETAINED, + ABORTED + } + + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ + private static AccountGameLogicIntakeSettlementReadEvidence evidence( + String namespace, int entryCount, Outcome outcome) { + var tenant = UUID.randomUUID(); + var version = UUID.randomUUID(); + var requestId = UUID.randomUUID(); + var commitId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var definitionsByFamily = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + definitionsByFamily.put(family, new ArrayList<>()); + definitionsByFamily.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(definitionsByFamily); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountEvidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.fromString(accountEvidence.scopeId()), + source, + List.of(accountEvidence)); + var operation = new GameLogicGameplayRuleIntakeOperation(namespace, authorization); + var terminal = + outcome == Outcome.RETAINED + ? GameLogicGameplayRuleIntakeTerminal.retained( + operation, + source.canonicalBytes(), + manifest.canonicalJson().getBytes(StandardCharsets.UTF_8)) + : GameLogicGameplayRuleIntakeTerminal.aborted(operation); + return new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization), + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..fc3a5bb34e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class AccountGameLogicIntakeSourceReadGrpcServiceTest { + @Test + void authenticatesExactGdBeforeDecoding() { + var owner = mock(AccountGameLogicIntakeSourceReadService.class); + var service = new AccountGameLogicIntakeSourceReadGrpcService(owner, "test"); + var malformed = GameLogicIntakeSourcePermissionRequest.getDefaultInstance(); + var missing = new Collector(); + service.readSourceScope(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String caller : + List.of("account-service", "game-logic-service", "world-management-service")) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSourceScope(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "game-design-service") + .run(() -> service.readSourceScope(malformed, otherNamespace)); + assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + var gd = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(malformed, gd)); + assertThat(gd.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void dispatchesOnlyMatchingProofMethodAndEchoesExactConfirmedRequest() { + var owner = mock(AccountGameLogicIntakeSourceReadService.class); + var service = new AccountGameLogicIntakeSourceReadGrpcService(owner, "test"); + var requests = requests(); + var prelim = GameLogicIntakeSourceReadProtoCodec.toRequest(requests.getFirst()); + var finalized = GameLogicIntakeSourceReadProtoCodec.toRequest(requests.getLast()); + var wrongFirst = new Collector(); + var wrongLast = new Collector(); + peer("test", "game-design-service") + .run( + () -> { + service.readSourceScope(finalized, wrongFirst); + service.readFinalizedIntake(prelim, wrongLast); + }); + assertThat(wrongFirst.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(wrongLast.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + when(owner.readSourceScope(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(owner.readFinalizedIntake(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + var first = new Collector(); + var last = new Collector(); + peer("test", "game-design-service") + .run( + () -> { + service.readSourceScope(prelim, first); + service.readFinalizedIntake(finalized, last); + }); + assertThat(first.response.getRequest()).isEqualTo(prelim); + assertThat(last.response.getRequest()).isEqualTo(finalized); + assertThat(first.response.getPermitted()).isTrue(); + assertThat(last.response.getPermitted()).isTrue(); + when(owner.readSourceScope(any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + var denied = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(prelim, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.response).isNull(); + } + + private static Context peer(String namespace, String service) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + } + + private static List requests() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + "test", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var source = selectedSource(selected); + var authorization = + new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return List.of( + GameLogicIntakeSourceReadEvidence.Request.create( + "test", + scope.intendedReader(), + scope.purpose(), + new GameplayRuleSourceReadEvidence.Preliminary(scope)), + GameLogicIntakeSourceReadEvidence.Request.create( + "test", + "spiffe://firemud/ns/test/sa/game-logic-service", + scope.purpose(), + new GameplayRuleSourceReadEvidence.Finalized(authorization))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + var revision = binding.revisions().getFirst(); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + revision.revisionOrder(), + "revisionId", + revision.revisionId().toString()))))); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + GameLogicIntakeSourcePermissionResponse response; + + public void onNext(GameLogicIntakeSourcePermissionResponse value) { + response = value; + } + + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java new file mode 100644 index 0000000000..06fca5ec21 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.StatusRuntimeException; +import java.time.Clock; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +class AccountGameLogicIntakeSourceReadServiceTest { + @Test + void ownerAuthenticatesPeerBeforeInspectingEitherProofOrAccessingStorage() { + var repository = mock(AccountGameLogicIntakeAuthorizationRepository.class); + var registry = mock(AccountControlUiCoordination.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new AccountGameLogicIntakeSourceReadService( + repository, registry, transactions, Clock.systemUTC(), "test"); + assertThatThrownBy(() -> service.readSourceScope(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy(() -> service.readFinalizedIntake(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + var wrongPeer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()); + var previous = wrongPeer.attach(); + try { + assertThatThrownBy(() -> service.readSourceScope(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy(() -> service.readFinalizedIntake(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + } finally { + wrongPeer.detach(previous); + } + verifyNoInteractions(repository, registry, transactions); + } + + @Test + void reservationFinalizationAndRecoveryCannotRunOutsideTheAccountOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountGameLogicIntakeAuthorizationRepository(dsl); + assertThatThrownBy(() -> repository.reserveSourceRead(null, null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner"); + assertThatThrownBy(() -> repository.finalizeSourceRead(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.recoverSourceRead(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.abortSourceRead(null)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index f604d2feeb..a1cca68f6d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -518,8 +518,7 @@ private static void runKeytool(String... arguments) throws Exception { private static X509Certificate readCertificate(Path path) throws Exception { try (var input = Files.newInputStream(path)) { - return (X509Certificate) - CertificateFactory.getInstance("X.509").generateCertificate(input); + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java new file mode 100644 index 0000000000..7742adfc40 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; + +/** Method-scoped protected metadata for the unchanged original creator credential. */ +public final class AccountGameLogicIntakeAuthorizationCredentials { + public static final int MAX_CREDENTIAL_BYTES = 16384; + public static final Context.Key CONTEXT_KEY = + Context.key("account-game-logic-intake-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-game-logic-intake-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Defer credential validation until the receiver has authenticated its caller. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountGameLogicIntakeAuthorizationCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (!validCredential(value)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 || bytes.length > MAX_CREDENTIAL_BYTES) throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "GameLogicIntakeCreatorCredential[redacted]"; + } + } + + public static Credential readAuthenticated(Metadata headers, String methodName) { + if (!allowedMethod(methodName)) throw invalid(); + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forAuthorize(String value) { + return forMethod( + value, + AccountGameLogicIntakeAuthorizationServiceGrpc.getAuthorizeIntakeMethod() + .getFullMethodName()); + } + + public static CallCredentials forRecover(String value) { + return forMethod( + value, + AccountGameLogicIntakeAuthorizationServiceGrpc.getRecoverIntakeMethod() + .getFullMethodName()); + } + + public static CallCredentials forAbort(String value) { + return forMethod( + value, + AccountGameLogicIntakeAuthorizationServiceGrpc.getAbortIntakeMethod().getFullMethodName()); + } + + private static CallCredentials forMethod(String value, String allowedMethod) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !allowedMethod.equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected Account intake authorization transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "GameLogicIntakeCreatorCallCredentials[redacted]"; + } + }; + } + + public static boolean allowedMethod(String methodName) { + return AccountGameLogicIntakeAuthorizationServiceGrpc.getAuthorizeIntakeMethod() + .getFullMethodName() + .equals(methodName) + || AccountGameLogicIntakeAuthorizationServiceGrpc.getRecoverIntakeMethod() + .getFullMethodName() + .equals(methodName) + || AccountGameLogicIntakeAuthorizationServiceGrpc.getAbortIntakeMethod() + .getFullMethodName() + .equals(methodName); + } + + private static boolean validCredential(String credential) { + return credential != null + && !credential.isEmpty() + && credential.length() <= MAX_CREDENTIAL_BYTES + && credential.chars().allMatch(value -> value > 32 && value < 127); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Game Logic intake credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java new file mode 100644 index 0000000000..cb88f0cc7c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Immutable original Account settlement; transport correlation is outside its identity. */ +public record AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal terminal) { + public static final String SCHEMA = "account-game-logic-intake-settlement/v1"; + // Preserve the original stored receipt envelope over the 16 MiB terminal budget. + public static final int MAX_CANONICAL_BYTES = + GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES + 1024; + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + public AccountGameLogicIntakeSettlementEvidence { + Objects.requireNonNull(terminal); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + if (out.size() > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Oversized settlement receipt"); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static AccountGameLogicIntakeSettlementEvidence fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Oversized settlement receipt"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var receipt = + new AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, receipt.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical settlement"); + return receipt; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java new file mode 100644 index 0000000000..c7ee6dd58a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed complete request echo and immutable canonical Account receipt transport. */ +public final class AccountGameLogicIntakeSettlementProtoCodec { + private AccountGameLogicIntakeSettlementProtoCodec() {} + + public static SettleGameLogicIntakeRequest toRequest( + AccountGameLogicIntakeSettlementReadEvidence.Request request) { + return SettleGameLogicIntakeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalIntakeAuthorization(ByteString.copyFrom(request.binding().canonicalBytes())) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + } + + public static AccountGameLogicIntakeSettlementReadEvidence.Request fromRequest( + SettleGameLogicIntakeRequest request) { + if (!request.getUnknownFields().asMap().isEmpty() + || request.getOriginalIntakeAuthorization().size() > 4 * 1024 * 1024) + throw new IllegalArgumentException("Unknown or oversized original intake authorization"); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var binding = + GameLogicIntakeAuthorizationBinding.fromStored( + request.getOriginalIntakeAuthorization().toByteArray()); + if (!binding.digest().equals(request.getIntakeAuthorizationDigest())) + throw new IllegalArgumentException("Changed original intake digest"); + return new AccountGameLogicIntakeSettlementReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + binding); + } + + public static SettleGameLogicIntakeResponse toResponse( + AccountGameLogicIntakeSettlementReadEvidence evidence) { + return SettleGameLogicIntakeResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setOriginalSettlementReceipt(ByteString.copyFrom(evidence.receipt().canonicalBytes())) + .setSettlementReceiptDigest(evidence.receipt().digest()) + .build(); + } + + public static AccountGameLogicIntakeSettlementReadEvidence fromResponse( + AccountGameLogicIntakeSettlementReadEvidence.Request request, + SettleGameLogicIntakeResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || response.getOriginalSettlementReceipt().size() + > AccountGameLogicIntakeSettlementEvidence.MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Changed or oversized settlement evidence"); + var receipt = + AccountGameLogicIntakeSettlementEvidence.fromStored( + response.getOriginalSettlementReceipt().toByteArray()); + if (!receipt.digest().equals(response.getSettlementReceiptDigest())) + throw new IllegalArgumentException("Changed settlement receipt digest"); + return new AccountGameLogicIntakeSettlementReadEvidence(request, receipt); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java new file mode 100644 index 0000000000..3fc4c8e5e9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Account-owned settlement production/recovery, invoked outside SQL by Game Design. */ +@FunctionalInterface +public interface AccountGameLogicIntakeSettlementReadClient { + AccountGameLogicIntakeSettlementReadEvidence read( + AccountGameLogicIntakeSettlementReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java new file mode 100644 index 0000000000..bc31949a76 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact Account receipt response; it grants no fresh intake authority. */ +public record AccountGameLogicIntakeSettlementReadEvidence( + Request request, AccountGameLogicIntakeSettlementEvidence receipt) { + public AccountGameLogicIntakeSettlementReadEvidence { + Objects.requireNonNull(request); + Objects.requireNonNull(receipt); + if (!request.targetNamespace().equals(receipt.terminal().operation().targetNamespace()) + || !Arrays.equals( + request.binding().canonicalBytes(), receipt.terminal().authorizationBytes())) + throw new IllegalArgumentException("Receipt differs from original intake authorization"); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported settlement schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) + throw new IllegalArgumentException("Separate transport correlation required"); + } + + public static Request create(String namespace, GameLogicIntakeAuthorizationBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java new file mode 100644 index 0000000000..403b56ae2a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact namespace and Account authorization identity for one independent GL source intake. */ +public record GameLogicGameplayRuleIntakeOperation( + String targetNamespace, GameLogicIntakeAuthorizationBinding authorization) { + public static final String SCHEMA = "game-logic-gameplay-rule-intake-operation/v1"; + + public GameLogicGameplayRuleIntakeOperation { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical intake namespace required"); + } + Objects.requireNonNull(authorization, "Original Account intake order required"); + } + + public byte[] canonicalBytes() { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, targetNamespace); + DraftAuthorizationFenceBinding.frame(output, authorization.canonicalBytes()); + return output.toByteArray(); + } + + public byte[] authorizationBytes() { + return authorization.canonicalBytes(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicGameplayRuleIntakeOperation fromStored(byte[] original) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(original); + reader.expect(SCHEMA); + var operation = + new GameLogicGameplayRuleIntakeOperation( + reader.text(), GameLogicIntakeAuthorizationBinding.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(original, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical GL intake operation"); + } + return operation; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java new file mode 100644 index 0000000000..3f92885987 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java @@ -0,0 +1,170 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Durable owner terminal. Empty/absent storage is represented separately from ABORTED. */ +public final class GameLogicGameplayRuleIntakeTerminal { + public static final int MAX_CANONICAL_BYTES = 16 * 1024 * 1024; + + /** + * A response carries at most 16 MiB terminal plus 4 MiB original order and bounded namespace, + * UUID, digests, and protobuf framing. 24 MiB includes that closed maximum's envelope overhead. + * Standalone servers must use the same limit; this is not a runtime-registration assertion. + */ + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + public static final String SCHEMA = "game-logic-gameplay-rule-intake-terminal/v1"; + + public enum Outcome { + RETAINED, + ABORTED + } + + private final GameLogicGameplayRuleIntakeOperation operation; + private final Outcome outcome; + private final byte[] authorizationBytes; + private final byte[] selectedSourceBytes; + private final byte[] manifestBytes; + + private GameLogicGameplayRuleIntakeTerminal( + GameLogicGameplayRuleIntakeOperation operation, + Outcome outcome, + byte[] authorizationBytes, + byte[] selectedSourceBytes, + byte[] manifestBytes) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.outcome = Objects.requireNonNull(outcome, "outcome"); + this.authorizationBytes = copy(authorizationBytes); + this.selectedSourceBytes = nullableCopy(selectedSourceBytes); + this.manifestBytes = nullableCopy(manifestBytes); + if (!Arrays.equals(this.authorizationBytes, operation.authorizationBytes())) { + throw new IllegalArgumentException("Terminal authorization differs from its operation"); + } + if (outcome == Outcome.RETAINED) { + if (this.selectedSourceBytes == null || this.manifestBytes == null) { + throw new IllegalArgumentException("Retained terminal requires source and manifest bytes"); + } + var source = + new GameplayRuleSelectedSource( + new String(this.selectedSourceBytes, StandardCharsets.UTF_8)); + if (!Arrays.equals(this.selectedSourceBytes, source.canonicalBytes()) + || !Arrays.equals( + this.selectedSourceBytes, operation.authorization().source().canonicalBytes()) + || !Arrays.equals( + this.manifestBytes, + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Retained source or manifest differs from authorization"); + } + } else if (this.selectedSourceBytes != null || this.manifestBytes != null) { + throw new IllegalArgumentException("Aborted terminal cannot claim retained source"); + } + } + + public static GameLogicGameplayRuleIntakeTerminal retained( + GameLogicGameplayRuleIntakeOperation operation, byte[] sourceBytes, byte[] manifestBytes) { + return new GameLogicGameplayRuleIntakeTerminal( + operation, Outcome.RETAINED, operation.authorizationBytes(), sourceBytes, manifestBytes); + } + + public static GameLogicGameplayRuleIntakeTerminal aborted( + GameLogicGameplayRuleIntakeOperation operation) { + return new GameLogicGameplayRuleIntakeTerminal( + operation, Outcome.ABORTED, operation.authorizationBytes(), null, null); + } + + public GameLogicGameplayRuleIntakeOperation operation() { + return operation; + } + + public Outcome outcome() { + return outcome; + } + + public byte[] authorizationBytes() { + return authorizationBytes.clone(); + } + + public byte[] selectedSourceBytes() { + return nullableCopy(selectedSourceBytes); + } + + public byte[] manifestBytes() { + return nullableCopy(manifestBytes); + } + + public String authorizationDigest() { + return operation.authorization().digest(); + } + + public String selectedSourceDigest() { + return selectedSourceBytes == null ? null : GameplayRuleManifest.sha256(selectedSourceBytes); + } + + public String manifestDigest() { + return manifestBytes == null ? null : GameplayRuleManifest.sha256(manifestBytes); + } + + public byte[] canonicalBytes() { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, outcome.name()); + DraftAuthorizationFenceBinding.frame(output, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, authorizationBytes); + frameOptional(output, selectedSourceBytes); + frameOptional(output, manifestBytes); + if (output.size() > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Terminal exceeds 16 MiB"); + return output.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicGameplayRuleIntakeTerminal fromStored(byte[] original) { + if (original == null || original.length == 0 || original.length > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Invalid terminal size"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(original); + reader.expect(SCHEMA); + Outcome outcome = Outcome.valueOf(reader.text()); + var operation = GameLogicGameplayRuleIntakeOperation.fromStored(reader.bytes()); + byte[] authorization = reader.bytes(); + byte[] source = readOptional(reader); + byte[] manifest = readOptional(reader); + reader.requireEnd(); + var terminal = + new GameLogicGameplayRuleIntakeTerminal( + operation, outcome, authorization, source, manifest); + if (!Arrays.equals(original, terminal.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical GL intake terminal"); + } + return terminal; + } + + private static void frameOptional(ByteArrayOutputStream output, byte[] value) { + DraftAuthorizationFenceBinding.frame(output, value == null ? "ABSENT" : "PRESENT"); + if (value != null) DraftAuthorizationFenceBinding.frame(output, value); + } + + private static byte[] readOptional(DraftAuthorizationFenceBinding.FrameReader reader) { + String presence = reader.text(); + if ("ABSENT".equals(presence)) return null; + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid optional GL intake terminal frame"); + } + return reader.bytes(); + } + + private static byte[] copy(byte[] value) { + return Objects.requireNonNull(value, "bytes").clone(); + } + + private static byte[] nullableCopy(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java new file mode 100644 index 0000000000..7fa89fbf1c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; + +/** Distinct GL retention permission input. Only Account's genuine producer may establish HELD. */ +public record GameLogicIntakeAuthorizationBinding( + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID actorAccountId, + GameplayRuleSelectedSource source, + List sources) { + public static final String SCHEMA = "account-game-logic-intake-authorization/v1"; + + public GameLogicIntakeAuthorizationBinding { + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.requireUuid(id); + Objects.requireNonNull(source); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) + throw new IllegalArgumentException("Complete distinct Account sources required"); + for (var value : sources) { + String scope = + switch (value.kind()) { + case ACCOUNT, GLOBAL_ROLES -> actorAccountId.toString(); + case TENANT -> tenantId(source).toString(); + case MEMBERSHIP -> actorAccountId + "/" + tenantId(source); + default -> null; + }; + if (scope != null && !scope.equals(value.scopeId())) + throw new IllegalArgumentException("Intake source differs from actor/tenant"); + } + } + + private static UUID tenantId(GameplayRuleSelectedSource source) { + return source.binding().target().canonicalTenantId(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public UUID tenantId() { + return tenantId(source); + } + + public UUID versionId() { + return source.binding().target().canonicalVersionId(); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.frame(out, id.toString()); + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (var value : sources) DraftAuthorizationFenceBinding.frame(out, value.canonicalBytes()); + if (out.size() > 4194304) throw new IllegalArgumentException("Intake order exceeds 4 MiB"); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicIntakeAuthorizationBinding fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 4194304) + throw new IllegalArgumentException("Invalid original intake order size"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + UUID operation = uuid(reader.text()), + fence = uuid(reader.text()), + request = uuid(reader.text()), + actor = uuid(reader.text()); + var source = new GameplayRuleSelectedSource(new String(reader.bytes(), StandardCharsets.UTF_8)); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + int count = Integer.parseInt(countText); + if (count > reader.remaining() / Integer.BYTES) + throw new IllegalArgumentException("Incomplete source vector"); + var sources = new java.util.ArrayList(); + for (int i = 0; i < count; i++) sources.add(SourceEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + var result = + new GameLogicIntakeAuthorizationBinding(operation, fence, request, actor, source, sources); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical intake order"); + return result; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java new file mode 100644 index 0000000000..070b7f8c0b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Explicit producer call and same-identity recovery/abort operations. */ +public interface GameLogicIntakeAuthorizationClient { + GameLogicIntakeAuthorizationEvidence.Result authorize( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); + + GameLogicIntakeAuthorizationEvidence.Result recover( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); + + GameLogicIntakeAuthorizationEvidence.Result abort( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java new file mode 100644 index 0000000000..8d43cfc7ff --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact closed producer request and bounded recovery result, without credential material. */ +public final class GameLogicIntakeAuthorizationEvidence { + public static final int MAX_SELECTION_BYTES = 4 * 1024 * 1024; + + private GameLogicIntakeAuthorizationEvidence() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + UUID intakeRequestId, + byte[] selectedDraftBinding) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || transportRequestId == null + || intakeRequestId == null + || transportRequestId.equals(intakeRequestId)) throw invalid(); + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + if (selectedDraftBinding == null + || selectedDraftBinding.length == 0 + || selectedDraftBinding.length > MAX_SELECTION_BYTES) throw invalid(); + selectedDraftBinding = selectedDraftBinding.clone(); + decodeSelection(selectedDraftBinding); + } + + public static Request create( + String namespace, UUID intakeRequestId, DraftCommitBinding selected) { + Objects.requireNonNull(selected); + return new Request( + 1, namespace, UUID.randomUUID(), intakeRequestId, selected.canonicalBytes()); + } + + @Override + public byte[] selectedDraftBinding() { + return selectedDraftBinding.clone(); + } + + public DraftCommitBinding selected() { + return decodeSelection(selectedDraftBinding); + } + + @Override + public String toString() { + return "GameLogicIntakeAuthorization.Request[redacted]"; + } + } + + public enum Outcome { + RESERVED, + FINALIZED, + ABORTED + } + + public record Result( + Request request, + Outcome outcome, + Optional sourceScope, + Optional authorization) { + public Result { + Objects.requireNonNull(request); + Objects.requireNonNull(outcome); + sourceScope = Objects.requireNonNull(sourceScope); + authorization = Objects.requireNonNull(authorization); + sourceScope.ifPresent( + scope -> { + if (!request.targetNamespace().equals(scope.targetNamespace()) + || !request.intakeRequestId().equals(scope.intakeRequestId()) + || !request.selected().equals(scope.selected())) throw invalid(); + }); + authorization.ifPresent( + binding -> { + if (!request.intakeRequestId().equals(binding.intakeRequestId()) + || !request.selected().equals(binding.source().binding())) throw invalid(); + }); + if (sourceScope.isPresent() && authorization.isPresent()) { + var scope = sourceScope.orElseThrow(); + var binding = authorization.orElseThrow(); + if (!scope.operationId().equals(binding.operationId()) + || !scope.fenceId().equals(binding.fenceId()) + || !scope.intakeRequestId().equals(binding.intakeRequestId()) + || !scope.actorAccountId().equals(binding.actorAccountId())) throw invalid(); + } + if (outcome == Outcome.FINALIZED && authorization.isEmpty()) throw invalid(); + if (outcome != Outcome.FINALIZED && (sourceScope.isEmpty() || authorization.isPresent())) + throw invalid(); + } + + public static Result authorized( + Request request, GameLogicIntakeAuthorizationBinding authorization) { + return new Result(request, Outcome.FINALIZED, Optional.empty(), Optional.of(authorization)); + } + } + + static DraftCommitBinding decodeSelection(byte[] bytes) { + try { + String json = new String(bytes, StandardCharsets.UTF_8); + var selection = + DraftCommitBinding.fromStored(json, DraftAuthorizationFenceBinding.digest(bytes)); + if (!Arrays.equals(bytes, selection.canonicalBytes())) throw invalid(); + return selection; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Game Logic intake authorization evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java new file mode 100644 index 0000000000..d9592f5e85 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed producer transport codec. The creator credential is never encoded in protobuf. */ +public final class GameLogicIntakeAuthorizationGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + private static final int MAX_SCOPE_BYTES = 4 * 1024 * 1024; + private static final int MAX_AUTHORIZATION_BYTES = 4 * 1024 * 1024; + + private GameLogicIntakeAuthorizationGrpcCodec() {} + + public static GameLogicIntakeAuthorizationRequest toRequest( + GameLogicIntakeAuthorizationEvidence.Request request) { + var wire = + GameLogicIntakeAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setSelectedDraftBinding(ByteString.copyFrom(request.selectedDraftBinding())) + .build(); + requireWireSize(wire.getSerializedSize()); + return wire; + } + + /** Invoke only after authenticating the exact same-namespace Game Design workload. */ + public static GameLogicIntakeAuthorizationEvidence.Request fromRequest( + GameLogicIntakeAuthorizationRequest wire) { + try { + noUnknown(wire); + requireWireSize(wire.getSerializedSize()); + if (wire.getSelectedDraftBinding().size() + > GameLogicIntakeAuthorizationEvidence.MAX_SELECTION_BYTES) throw invalid(); + var request = + new GameLogicIntakeAuthorizationEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + canonicalUuid(wire.getTransportRequestId()), + canonicalUuid(wire.getIntakeRequestId()), + wire.getSelectedDraftBinding().toByteArray()); + if (!toRequest(request).equals(wire)) throw invalid(); + return request; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + public static GameLogicIntakeAuthorizationResponse toResponse( + GameLogicIntakeAuthorizationEvidence.Result result) { + var builder = + GameLogicIntakeAuthorizationResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setOutcome(toWire(result.outcome())); + result + .sourceScope() + .ifPresent( + scope -> + builder.setPreliminarySourceScope(ByteString.copyFrom(scope.canonicalBytes()))); + result + .authorization() + .ifPresent( + binding -> + builder.setFinalizedIntakeAuthorization( + ByteString.copyFrom(binding.canonicalBytes()))); + var response = builder.build(); + requireWireSize(response.getSerializedSize()); + return response; + } + + public static GameLogicIntakeAuthorizationEvidence.Result fromResponse( + GameLogicIntakeAuthorizationEvidence.Request request, + GameLogicIntakeAuthorizationResponse wire) { + try { + noUnknown(wire); + requireWireSize(wire.getSerializedSize()); + if (!wire.hasRequest() || !toRequest(request).equals(wire.getRequest())) throw invalid(); + Optional scope = Optional.empty(); + Optional authorization = Optional.empty(); + if (wire.getPreliminarySourceScope().size() > MAX_SCOPE_BYTES + || wire.getFinalizedIntakeAuthorization().size() > MAX_AUTHORIZATION_BYTES) + throw invalid(); + if (!wire.getPreliminarySourceScope().isEmpty()) + scope = + Optional.of( + GameLogicIntakeSourceReadScope.fromStored( + wire.getPreliminarySourceScope().toByteArray())); + if (!wire.getFinalizedIntakeAuthorization().isEmpty()) + authorization = + Optional.of( + GameLogicIntakeAuthorizationBinding.fromStored( + wire.getFinalizedIntakeAuthorization().toByteArray())); + return new GameLogicIntakeAuthorizationEvidence.Result( + request, fromWire(wire.getOutcome()), scope, authorization); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static UUID canonicalUuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } + + private static GameLogicIntakeAuthorizationResponse.Outcome toWire( + GameLogicIntakeAuthorizationEvidence.Outcome outcome) { + return switch (outcome) { + case RESERVED -> GameLogicIntakeAuthorizationResponse.Outcome.RESERVED; + case FINALIZED -> GameLogicIntakeAuthorizationResponse.Outcome.FINALIZED; + case ABORTED -> GameLogicIntakeAuthorizationResponse.Outcome.ABORTED; + }; + } + + private static GameLogicIntakeAuthorizationEvidence.Outcome fromWire( + GameLogicIntakeAuthorizationResponse.Outcome outcome) { + return switch (outcome) { + case RESERVED -> GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED; + case FINALIZED -> GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED; + case ABORTED -> GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED; + default -> throw invalid(); + }; + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static void requireWireSize(int size) { + if (size > MAX_WIRE_BYTES) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Game Logic intake authorization transport"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java new file mode 100644 index 0000000000..dadb56b705 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** + * Explicit file-backed mTLS client for the exact same-namespace Account intake authorization read. + */ +public final class GameLogicIntakeAuthorizationReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameLogicIntakeAuthorizationReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameLogicIntakeAuthorizationReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Account GL intake authorization read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account GL intake authorization read stub unavailable"); + initialized = true; + } + + /** Returns a validated HELD result only after exact Account server mTLS identity verification. */ + public GameLogicIntakeAuthorizationReadEvidence read( + GameLogicIntakeAuthorizationReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Account intake transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account GL intake authorization read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldGameLogicIntakeAuthorization( + GameLogicIntakeAuthorizationReadGrpcCodec.toRequest(request)); + try { + return GameLogicIntakeAuthorizationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account returned invalid COMMIT_ORDER evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeAuthorizationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account GL intake authorization read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java new file mode 100644 index 0000000000..5ce523813d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Lookup tuple only. HELD must come from the authenticated Account read. */ +public record GameLogicIntakeAuthorizationReadEvidence(Request request) { + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported intake read schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) + throw new IllegalArgumentException("Separate transport correlation required"); + } + + public static Request create(String namespace, GameLogicIntakeAuthorizationBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..3c68268515 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Exact closed HELD wire mapping; authentication precedes decoding at the receiver. */ +public final class GameLogicIntakeAuthorizationReadGrpcCodec { + private GameLogicIntakeAuthorizationReadGrpcCodec() {} + + public static ReadHeldGameLogicIntakeAuthorizationRequest toRequest( + GameLogicIntakeAuthorizationReadEvidence.Request value) { + return ReadHeldGameLogicIntakeAuthorizationRequest.newBuilder() + .setSchemaVersion(value.schemaVersion()) + .setTargetNamespace(value.targetNamespace()) + .setReadRequestId(value.readRequestId().toString()) + .setOriginalIntakeAuthorization(ByteString.copyFrom(value.binding().canonicalBytes())) + .setIntakeAuthorizationDigest(value.binding().digest()) + .build(); + } + + public static GameLogicIntakeAuthorizationReadEvidence.Request fromRequest( + ReadHeldGameLogicIntakeAuthorizationRequest value) { + if (!value.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Unknown intake read fields"); + DraftAuthorizationFenceBinding.canonicalUuid(value.getReadRequestId()); + var binding = + GameLogicIntakeAuthorizationBinding.fromStored( + value.getOriginalIntakeAuthorization().toByteArray()); + if (!binding.digest().equals(value.getIntakeAuthorizationDigest())) + throw new IllegalArgumentException("Changed intake digest"); + return new GameLogicIntakeAuthorizationReadEvidence.Request( + value.getSchemaVersion(), + value.getTargetNamespace(), + UUID.fromString(value.getReadRequestId()), + binding); + } + + public static ReadHeldGameLogicIntakeAuthorizationResponse toHeldResponse( + GameLogicIntakeAuthorizationReadEvidence.Request request) { + return ReadHeldGameLogicIntakeAuthorizationResponse.newBuilder() + .setRequest(toRequest(request)) + .setHeld(true) + .build(); + } + + public static GameLogicIntakeAuthorizationReadEvidence fromResponse( + GameLogicIntakeAuthorizationReadEvidence.Request request, + ReadHeldGameLogicIntakeAuthorizationResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getHeld()) + throw new IllegalArgumentException("Exact held intake response required"); + return new GameLogicIntakeAuthorizationReadEvidence(request); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java new file mode 100644 index 0000000000..85bc7978e2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Transport boundary for exact Game Logic selected-source retention. */ +public interface GameLogicIntakeRetainClient { + GameLogicIntakeRetainEvidence retain(GameLogicIntakeRetainEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java new file mode 100644 index 0000000000..b41d580b65 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact request and terminal evidence for one transport attempt to retain selected rule input. */ +public record GameLogicIntakeRetainEvidence( + Request request, GameLogicGameplayRuleIntakeTerminal terminal) { + public static final int MAX_AUTHORIZATION_BYTES = 4 * 1024 * 1024; + + public GameLogicIntakeRetainEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(terminal, "terminal"); + if (!request.targetNamespace().equals(terminal.operation().targetNamespace()) + || !Arrays.equals(request.originalAuthorizationBytes(), terminal.authorizationBytes()) + || !request.authorizationDigest().equals(terminal.authorizationDigest())) { + throw new IllegalArgumentException( + "Terminal differs from exact namespace or original authorization"); + } + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID correlationId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Supported retain schema and namespace required"); + } + DraftAuthorizationFenceBinding.requireUuid(correlationId); + Objects.requireNonNull(binding, "binding"); + if (binding.canonicalBytes().length > MAX_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Original intake authorization exceeds 4 MiB"); + } + if (correlationId.equals(binding.operationId()) + || correlationId.equals(binding.fenceId()) + || correlationId.equals(binding.intakeRequestId())) { + throw new IllegalArgumentException("Separate transport correlation required"); + } + } + + public static Request create( + String targetNamespace, GameLogicIntakeAuthorizationBinding binding) { + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(binding.operationId()) + || correlation.equals(binding.fenceId()) + || correlation.equals(binding.intakeRequestId())); + return new Request(1, targetNamespace, correlation, binding); + } + + public byte[] originalAuthorizationBytes() { + return binding.canonicalBytes(); + } + + public String authorizationDigest() { + return binding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && correlationId.equals(other.correlationId) + && Arrays.equals(originalAuthorizationBytes(), other.originalAuthorizationBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, + targetNamespace, + correlationId, + Arrays.hashCode(originalAuthorizationBytes())); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java new file mode 100644 index 0000000000..5090b15279 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; + +/** Closed request echo and canonical original-terminal mapping for the retain transport. */ +public final class GameLogicIntakeRetainProtoCodec { + public static final int MAX_WIRE_BYTES = GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES; + + private GameLogicIntakeRetainProtoCodec() {} + + public static RetainGameplayRuleIntakeRequest toRequest( + GameLogicIntakeRetainEvidence.Request request) { + var wire = + RetainGameplayRuleIntakeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setCorrelationId(request.correlationId().toString()) + .setOriginalIntakeAuthorization( + ByteString.copyFrom(request.originalAuthorizationBytes())) + .setIntakeAuthorizationDigest(request.authorizationDigest()) + .build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) { + throw new IllegalArgumentException("Oversized intake retain request"); + } + return wire; + } + + /** Call only after authenticating the exact same-namespace Game Design workload. */ + public static GameLogicIntakeRetainEvidence.Request fromRequest( + RetainGameplayRuleIntakeRequest request) { + if (request == null + || !request.getUnknownFields().asMap().isEmpty() + || request.getSerializedSize() > MAX_WIRE_BYTES + || request.getOriginalIntakeAuthorization().isEmpty() + || request.getOriginalIntakeAuthorization().size() + > GameLogicIntakeRetainEvidence.MAX_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Unknown or oversized intake retain request"); + } + DraftAuthorizationFenceBinding.canonicalUuid(request.getCorrelationId()); + var bytes = request.getOriginalIntakeAuthorization().toByteArray(); + var binding = GameLogicIntakeAuthorizationBinding.fromStored(bytes); + if (!Arrays.equals(bytes, binding.canonicalBytes()) + || !binding.digest().equals(request.getIntakeAuthorizationDigest())) { + throw new IllegalArgumentException("Changed original intake authorization"); + } + return new GameLogicIntakeRetainEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getCorrelationId()), + binding); + } + + public static RetainGameplayRuleIntakeResponse toResponse( + GameLogicIntakeRetainEvidence evidence) { + var terminal = evidence.terminal(); + byte[] terminalBytes = terminal.canonicalBytes(); + if (terminalBytes.length > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Oversized original intake terminal"); + } + var response = + RetainGameplayRuleIntakeResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setOriginalTerminal(ByteString.copyFrom(terminalBytes)) + .setTerminalDigest(terminal.digest()) + .build(); + if (response.getSerializedSize() > MAX_WIRE_BYTES) { + throw new IllegalArgumentException("Oversized intake retain response"); + } + return response; + } + + public static GameLogicIntakeRetainEvidence fromResponse( + GameLogicIntakeRetainEvidence.Request request, RetainGameplayRuleIntakeResponse response) { + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || response.getSerializedSize() > MAX_WIRE_BYTES + || !response.hasRequest() + || !response.getRequest().getUnknownFields().asMap().isEmpty() + || !toRequest(request).equals(response.getRequest()) + || response.getOriginalTerminal().isEmpty() + || response.getOriginalTerminal().size() + > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Changed intake retain correlation or terminal size"); + } + var terminal = + GameLogicGameplayRuleIntakeTerminal.fromStored( + response.getOriginalTerminal().toByteArray()); + if (!terminal.digest().equals(response.getTerminalDigest())) { + throw new IllegalArgumentException("Changed original intake terminal digest"); + } + return new GameLogicIntakeRetainEvidence(request, terminal); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java new file mode 100644 index 0000000000..aa29ff84ef --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Dedicated authenticated Account owner readback. */ +public interface GameLogicIntakeSourceReadClient { + GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java new file mode 100644 index 0000000000..62e63ab02c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact Account owner confirmation, never a locally minted permission. */ +public record GameLogicIntakeSourceReadEvidence(Request request) { + public GameLogicIntakeSourceReadEvidence { + Objects.requireNonNull(request); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + String intendedReader, + String purpose, + GameplayRuleSourceReadEvidence.Proof proof) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException( + "Canonical source permission schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(proof); + String service = + proof instanceof GameplayRuleSourceReadEvidence.Preliminary + ? "account-service" + : "game-logic-service"; + if (!("spiffe://firemud/ns/" + targetNamespace + "/sa/" + service).equals(intendedReader) + || !GameLogicIntakeSourceReadScope.PURPOSE.equals(purpose)) + throw new IllegalArgumentException("Exact reader and closed purpose required"); + if (proof instanceof GameplayRuleSourceReadEvidence.Preliminary preliminary + && (!targetNamespace.equals(preliminary.scope().targetNamespace()) + || !intendedReader.equals(preliminary.scope().intendedReader()) + || !purpose.equals(preliminary.scope().purpose()))) + throw new IllegalArgumentException("Preliminary scope differs"); + if (readRequestId.equals(proof.operationId()) + || readRequestId.equals(proof.intakeRequestId()) + || readRequestId.equals(proof.fenceId()) + || readRequestId.equals(proof.selected().requestId()) + || readRequestId.equals(proof.selected().commitId())) + throw new IllegalArgumentException("Independent read correlation required"); + } + + public static Request create( + String namespace, + String reader, + String purpose, + GameplayRuleSourceReadEvidence.Proof proof) { + return new Request(1, namespace, UUID.randomUUID(), reader, purpose, proof); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java new file mode 100644 index 0000000000..015ed9566c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed canonical proof mapping; decode only after authenticating GD. */ +public final class GameLogicIntakeSourceReadProtoCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private GameLogicIntakeSourceReadProtoCodec() {} + + public static GameLogicIntakeSourcePermissionRequest toRequest( + GameLogicIntakeSourceReadEvidence.Request request) { + var builder = + GameLogicIntakeSourcePermissionRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setPurpose(request.purpose()) + .setAuthorizationProofDigest(request.proof().digest()); + var bytes = ByteString.copyFrom(request.proof().canonicalBytes()); + if (request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary) + builder.setPreliminarySourceScope(bytes); + else builder.setFinalizedIntakeAuthorization(bytes); + var wire = builder.build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized Account source permission request"); + return wire; + } + + public static GameLogicIntakeSourceReadEvidence.Request fromRequest( + GameLogicIntakeSourcePermissionRequest request) { + if (request == null + || request.getSerializedSize() > MAX_WIRE_BYTES + || !request.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Unknown or oversized permission fields"); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + GameplayRuleSourceReadEvidence.Proof proof = + switch (request.getAuthorizationProofCase()) { + case PRELIMINARY_SOURCE_SCOPE -> + new GameplayRuleSourceReadEvidence.Preliminary( + GameLogicIntakeSourceReadScope.fromStored( + request.getPreliminarySourceScope().toByteArray())); + case FINALIZED_INTAKE_AUTHORIZATION -> + new GameplayRuleSourceReadEvidence.Finalized( + GameLogicIntakeAuthorizationBinding.fromStored( + request.getFinalizedIntakeAuthorization().toByteArray())); + default -> throw new IllegalArgumentException("Source permission proof required"); + }; + if (!proof.digest().equals(request.getAuthorizationProofDigest())) + throw new IllegalArgumentException("Changed proof digest"); + return new GameLogicIntakeSourceReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + request.getIntendedReader(), + request.getPurpose(), + proof); + } + + public static GameLogicIntakeSourcePermissionResponse toResponse( + GameLogicIntakeSourceReadEvidence.Request request) { + var wire = + GameLogicIntakeSourcePermissionResponse.newBuilder() + .setRequest(toRequest(request)) + .setPermitted(true) + .build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized Account source permission response"); + return wire; + } + + public static GameLogicIntakeSourceReadEvidence fromResponse( + GameLogicIntakeSourceReadEvidence.Request request, + GameLogicIntakeSourcePermissionResponse response) { + if (response == null + || response.getSerializedSize() > MAX_WIRE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getPermitted()) + throw new IllegalArgumentException("Exact Account source permission confirmation required"); + return new GameLogicIntakeSourceReadEvidence(request); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java new file mode 100644 index 0000000000..101a2492de --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact preliminary Account source-read scope. Never authorizes Game Logic retention. */ +public record GameLogicIntakeSourceReadScope( + String targetNamespace, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID actorAccountId, + DraftCommitBinding selected, + String intendedReader, + String purpose) { + public static final String SCHEMA = "account-game-logic-intake-source-read/v1"; + public static final String PURPOSE = "GAME_LOGIC_INTAKE_SOURCE"; + private static final int MAX_BYTES = 4194304; + + public GameLogicIntakeSourceReadScope { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Canonical scope namespace required"); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.requireUuid(id); + Objects.requireNonNull(selected); + if (!("spiffe://firemud/ns/" + targetNamespace + "/sa/account-service").equals(intendedReader) + || !PURPOSE.equals(purpose)) + throw new IllegalArgumentException("Exact preliminary Account reader and purpose required"); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.frame(out, id.toString()); + DraftAuthorizationFenceBinding.frame(out, selected.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selected.digest()); + DraftAuthorizationFenceBinding.frame(out, intendedReader); + DraftAuthorizationFenceBinding.frame(out, purpose); + if (out.size() > MAX_BYTES) throw new IllegalArgumentException("Source scope exceeds 4 MiB"); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicIntakeSourceReadScope fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) + throw new IllegalArgumentException("Invalid source scope size"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var namespace = reader.text(); + var operation = uuid(reader.text()); + var fence = uuid(reader.text()); + var request = uuid(reader.text()); + var actor = uuid(reader.text()); + var selected = + DraftCommitBinding.fromStored( + new String(reader.bytes(), StandardCharsets.UTF_8), reader.text()); + var result = + new GameLogicIntakeSourceReadScope( + namespace, operation, fence, request, actor, selected, reader.text(), reader.text()); + reader.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical source scope"); + return result; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java new file mode 100644 index 0000000000..900069c6f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; + +/** Explicit file-backed mTLS client for the exact same-namespace Game Logic terminal read. */ +public final class GameLogicIntakeTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameLogicIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameLogicIntakeTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Game Logic intake terminal read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Game Logic intake terminal read stub unavailable"); + initialized = true; + } + + /** + * Returns a validated terminal or explicit absence after exact Game Logic server mTLS + * verification. + */ + public GameLogicIntakeTerminalReadEvidence read( + GameLogicIntakeTerminalReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Game Logic terminal transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Logic intake terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameplayRuleIntakeTerminal( + GameLogicIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Game Logic returned invalid terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameLogicService(); + } + + @Override + protected String defaultTarget() { + return "game-logic-service:6565"; + } + + @Override + protected GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service"; + return GameLogicGameplayRuleIntakeTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Logic intake terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Game Logic intake terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Logic intake terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Logic intake terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Logic intake terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Logic intake terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java new file mode 100644 index 0000000000..f039ee5405 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Absence is a successful lookup result, never an abort or permission to release participation. */ +public record GameLogicIntakeTerminalReadEvidence( + Request request, Optional terminal) { + public GameLogicIntakeTerminalReadEvidence { + Objects.requireNonNull(request); + Objects.requireNonNull(terminal); + terminal.ifPresent( + value -> { + var expected = + new GameLogicGameplayRuleIntakeOperation( + request.targetNamespace(), request.binding()); + if (!Arrays.equals(expected.canonicalBytes(), value.operation().canonicalBytes())) + throw new IllegalArgumentException("Terminal differs from exact original intake"); + }); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported terminal read schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) + throw new IllegalArgumentException("Separate transport correlation required"); + } + + public static Request create(String namespace, GameLogicIntakeAuthorizationBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..09c6755f5c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; + +/** Closed exact request echo and canonical original terminal mapping. */ +public final class GameLogicIntakeTerminalReadGrpcCodec { + private GameLogicIntakeTerminalReadGrpcCodec() {} + + public static ReadGameplayRuleIntakeTerminalRequest toRequest( + GameLogicIntakeTerminalReadEvidence.Request request) { + return ReadGameplayRuleIntakeTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalIntakeAuthorization(ByteString.copyFrom(request.binding().canonicalBytes())) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + } + + public static GameLogicIntakeTerminalReadEvidence.Request fromRequest( + ReadGameplayRuleIntakeTerminalRequest request) { + if (!request.getUnknownFields().asMap().isEmpty() + || request.getOriginalIntakeAuthorization().size() > 4194304) + throw new IllegalArgumentException("Unknown or oversized terminal lookup"); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var binding = + GameLogicIntakeAuthorizationBinding.fromStored( + request.getOriginalIntakeAuthorization().toByteArray()); + if (!binding.digest().equals(request.getIntakeAuthorizationDigest())) + throw new IllegalArgumentException("Changed original intake digest"); + return new GameLogicIntakeTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + binding); + } + + public static ReadGameplayRuleIntakeTerminalResponse toResponse( + GameLogicIntakeTerminalReadEvidence evidence) { + var response = + ReadGameplayRuleIntakeTerminalResponse.newBuilder() + .setRequest(toRequest(evidence.request())); + if (evidence.terminal().isEmpty()) return response.setAbsent(true).build(); + var terminal = evidence.terminal().orElseThrow(); + byte[] bytes = terminal.canonicalBytes(); + if (bytes.length > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Oversized original terminal"); + return response + .setOriginalTerminal(ByteString.copyFrom(bytes)) + .setTerminalDigest(terminal.digest()) + .build(); + } + + public static GameLogicIntakeTerminalReadEvidence fromResponse( + GameLogicIntakeTerminalReadEvidence.Request request, + ReadGameplayRuleIntakeTerminalResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest())) + throw new IllegalArgumentException("Changed terminal read correlation"); + return switch (response.getResultCase()) { + case ABSENT -> { + if (!response.getAbsent() || !response.getTerminalDigest().isEmpty()) + throw new IllegalArgumentException("Invalid absence evidence"); + yield new GameLogicIntakeTerminalReadEvidence(request, Optional.empty()); + } + case ORIGINAL_TERMINAL -> { + var terminal = + GameLogicGameplayRuleIntakeTerminal.fromStored( + response.getOriginalTerminal().toByteArray()); + if (!terminal.digest().equals(response.getTerminalDigest())) + throw new IllegalArgumentException("Changed terminal digest"); + yield new GameLogicIntakeTerminalReadEvidence(request, Optional.of(terminal)); + } + default -> throw new IllegalArgumentException("Explicit owner result required"); + }; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java new file mode 100644 index 0000000000..6e0277554f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** + * Exact bounded binding between a full-version publication read and its GL intake authorization. + * + *

This value preserves bytes and checks their selected tenant and Game Design Version row + * correlation. Constructing it does not authenticate Account or Game Design, establish that Account + * issued the order, prove Game Logic retained a manifest, or authorize publication or runtime + * activation. + */ +public final class GameLogicPublicationSourceReadBinding { + public static final String SCHEMA = "game-logic-publication-source-read/v1"; + public static final int MAX_PUBLICATION_REQUEST_BYTES = 4096; + public static final int MAX_AUTHORIZATION_BYTES = 4 * 1024 * 1024; + public static final int MAX_TOTAL_BYTES = + maxTotalBytes(SCHEMA, MAX_PUBLICATION_REQUEST_BYTES, MAX_AUTHORIZATION_BYTES); + + private static final byte[] SCHEMA_BYTES = SCHEMA.getBytes(StandardCharsets.US_ASCII); + + private final PublicationDigestRequestBinding publicationRequest; + private final GameLogicIntakeAuthorizationBinding authorization; + private final byte[] canonicalBytes; + private final String digest; + + /** Creates the exact source-read binding from its canonical component bindings. */ + public GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding publicationRequest, + GameLogicIntakeAuthorizationBinding authorization) { + this.publicationRequest = Objects.requireNonNull(publicationRequest, "publicationRequest"); + this.authorization = Objects.requireNonNull(authorization, "authorization"); + requireMatchingFullVersion(publicationRequest, authorization); + byte[] publicationBytes = publicationRequest.canonicalPreimage(); + byte[] authorizationBytes = authorization.canonicalBytes(); + requireComponentBounds(publicationBytes.length, authorizationBytes.length); + this.canonicalBytes = encode(publicationBytes, authorizationBytes); + this.digest = sha256(canonicalBytes); + } + + /** Creates the binding from the complete canonical Account intake-authorization bytes. */ + public GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding publicationRequest, byte[] authorizationBytes) { + this(publicationRequest, decodeAuthorization(authorizationBytes)); + } + + /** + * Reconstructs a stored binding, enforcing exact frame grammar and complete canonical equality. + */ + public static GameLogicPublicationSourceReadBinding fromStored( + PublicationDigestRequestBinding publicationRequest, byte[] stored) { + Objects.requireNonNull(publicationRequest, "publicationRequest"); + if (stored == null || stored.length == 0 || stored.length > MAX_TOTAL_BYTES) { + throw new IllegalArgumentException("Invalid publication source-read binding size"); + } + + int offset = readAndRequireSchema(stored); + Frame publicationFrame = readFrame(stored, offset, MAX_PUBLICATION_REQUEST_BYTES); + offset = publicationFrame.nextOffset(); + byte[] expectedPublication = publicationRequest.canonicalPreimage(); + if (!Arrays.equals(publicationFrame.bytes(), expectedPublication)) { + throw new IllegalArgumentException("Stored publication request differs from binding"); + } + + Frame authorizationFrame = readFrame(stored, offset, MAX_AUTHORIZATION_BYTES); + if (authorizationFrame.nextOffset() != stored.length) { + throw new IllegalArgumentException("Trailing publication source-read binding bytes"); + } + GameLogicIntakeAuthorizationBinding authorization = + decodeAuthorization(authorizationFrame.bytes()); + GameLogicPublicationSourceReadBinding result = + new GameLogicPublicationSourceReadBinding(publicationRequest, authorization); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical publication source-read binding"); + } + return result; + } + + public PublicationDigestRequestBinding publicationRequest() { + return publicationRequest; + } + + public GameLogicIntakeAuthorizationBinding authorization() { + return authorization; + } + + /** Returns a defensive copy of the exact three-frame preimage. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Returns the lowercase SHA-256 digest of {@link #canonicalBytes()}. */ + public String digest() { + return digest; + } + + private static void requireMatchingFullVersion( + PublicationDigestRequestBinding publicationRequest, + GameLogicIntakeAuthorizationBinding authorization) { + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException("Only full-version publication reads are supported"); + } + UUID publicationTenant; + try { + publicationTenant = UUID.fromString(publicationRequest.tenantId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Publication tenant must be the canonical GL tenant UUID", malformed); + } + if (!publicationTenant.toString().equals(publicationRequest.tenantId()) + || !publicationTenant.equals(authorization.tenantId())) { + throw new IllegalArgumentException("Publication tenant differs from retained GL source"); + } + String selectedVersionRowId = + Long.toString(authorization.source().binding().target().gameDesignVersionRowId()); + if (!selectedVersionRowId.equals(publicationRequest.versionId())) { + throw new IllegalArgumentException("Publication version differs from selected GL source"); + } + } + + private static byte[] encode(byte[] publicationRequestBytes, byte[] authorizationBytes) { + int totalBytes = + encodedLength(SCHEMA_BYTES.length) + + encodedLength(publicationRequestBytes.length) + + encodedLength(authorizationBytes.length); + if (totalBytes > MAX_TOTAL_BYTES) { + throw new IllegalArgumentException("Publication source-read binding exceeds total limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(totalBytes); + appendFrame(output, SCHEMA_BYTES); + appendFrame(output, publicationRequestBytes); + appendFrame(output, authorizationBytes); + byte[] encoded = output.toByteArray(); + if (encoded.length != totalBytes) { + throw new IllegalStateException("Publication source-read frame length calculation diverged"); + } + return encoded; + } + + private static int readAndRequireSchema(byte[] stored) { + Frame schema = readFrame(stored, 0, SCHEMA_BYTES.length); + if (!Arrays.equals(schema.bytes(), SCHEMA_BYTES)) { + throw new IllegalArgumentException("Unsupported publication source-read binding schema"); + } + return schema.nextOffset(); + } + + private static Frame readFrame(byte[] stored, int offset, int maximumLength) { + if (offset < 0 || offset >= stored.length) { + throw new IllegalArgumentException("Missing publication source-read frame"); + } + int colon = offset; + int length = 0; + while (colon < stored.length && stored[colon] != ':') { + int digit = stored[colon] - '0'; + if (digit < 0 + || digit > 9 + || (colon == offset + && digit == 0 + && colon + 1 < stored.length + && stored[colon + 1] != ':')) { + throw new IllegalArgumentException("Noncanonical publication source-read frame length"); + } + if (digit > maximumLength || length > (maximumLength - digit) / 10) { + throw new IllegalArgumentException("Publication source-read frame exceeds limit"); + } + length = length * 10 + digit; + colon++; + } + if (colon == offset || colon >= stored.length || stored[colon] != ':') { + throw new IllegalArgumentException("Malformed publication source-read frame length"); + } + int contentStart = colon + 1; + if (length == 0 || length > stored.length - contentStart) { + throw new IllegalArgumentException("Truncated publication source-read frame"); + } + int nextOffset = contentStart + length; + return new Frame(Arrays.copyOfRange(stored, contentStart, nextOffset), nextOffset); + } + + private static void requireComponentBounds(int publicationLength, int authorizationLength) { + if (publicationLength == 0 + || publicationLength > MAX_PUBLICATION_REQUEST_BYTES + || authorizationLength == 0 + || authorizationLength > MAX_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Publication source-read component exceeds limit"); + } + } + + private static GameLogicIntakeAuthorizationBinding decodeAuthorization(byte[] stored) { + if (stored == null || stored.length == 0 || stored.length > MAX_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Invalid Account intake-authorization size"); + } + try { + return GameLogicIntakeAuthorizationBinding.fromStored(stored); + } catch (IllegalArgumentException malformed) { + throw malformed; + } catch (RuntimeException corruptStoredBinding) { + throw new IllegalArgumentException( + "Invalid stored Account intake authorization", corruptStoredBinding); + } + } + + private static int maxTotalBytes(String schema, int publicationLength, int authorizationLength) { + int schemaLength = schema.getBytes(StandardCharsets.US_ASCII).length; + return Math.addExact( + Math.addExact(schemaLength, publicationLength + authorizationLength), + Math.addExact( + frameOverhead(schemaLength), + Math.addExact(frameOverhead(publicationLength), frameOverhead(authorizationLength)))); + } + + private static int encodedLength(int contentLength) { + return Math.addExact(contentLength, frameOverhead(contentLength)); + } + + private static int frameOverhead(int contentLength) { + int digits = 1; + for (int value = contentLength; value >= 10; value /= 10) digits++; + return digits + 1; + } + + private static void appendFrame(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record Frame(byte[] bytes, int nextOffset) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodec.java new file mode 100644 index 0000000000..93b5091300 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodec.java @@ -0,0 +1,358 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestResponse; + +/** + * Bounded exact protobuf mapping for the separate full-version publication source selection. + * + *

This codec preserves and correlates the Account authorization bytes and the exact retained + * Game Logic terminal. Byte integrity alone does not authenticate Account issuance, prove that Game + * Logic actually retained the terminal, grant authority, or establish publication approval. Callers + * may decode the terminal namespace against their configured authenticated namespace via {@link + * #fromResponse(GameLogicPublicationSourceReadBinding, GetDraftDesignDigestResponse, String)}; the + * two-argument overload preserves the terminal's namespace but does not authenticate it. + * + *

{@link #MAX_WIRE_BYTES} bounds the serialized protobuf message itself. It does not include any + * transport envelope or future protocol framing. + */ +public final class GameLogicPublicationSourceReadGrpcCodec { + /** Maximum serialized size of this protobuf request or response. */ + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + /** Maximum source binding bytes, including its canonical frame overhead. */ + public static final int MAX_BINDING_BYTES = GameLogicPublicationSourceReadBinding.MAX_TOTAL_BYTES; + + /** Maximum canonical original retained-terminal bytes. */ + public static final int MAX_TERMINAL_BYTES = + GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES; + + public static final int DIGEST_SCHEMA_VERSION = 1; + public static final String CANONICALIZATION = "RFC8785"; + + private GameLogicPublicationSourceReadGrpcCodec() {} + + /** Encodes a request for this binding's exact full-version publication selection. */ + public static GetDraftDesignDigestRequest toRequest( + GameLogicPublicationSourceReadBinding binding) { + Objects.requireNonNull(binding, "binding"); + requireFullVersion(binding); + byte[] bindingBytes = binding.canonicalBytes(); + requireBindingSize(bindingBytes.length); + PublicationDigestRequestBinding publication = binding.publicationRequest(); + int expectedWireSize = + stringFieldSize(1, publication.tenantId()) + + stringFieldSize(2, publication.versionId()) + + stringFieldSize(5, publication.publishRequestId()) + + stringFieldSize(6, publication.derivedWorkflowIdentity()) + + stringFieldSize(7, publication.requestDigest()) + + bytesFieldSize(8, bindingBytes.length) + + stringFieldSize(9, binding.digest()); + requireWireSize(expectedWireSize); + + GetDraftDesignDigestRequest request = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId(publication.tenantId()) + .setVersionId(publication.versionId()) + .setBaseVersionId(publication.baseVersionId()) + .setPublishRequestId(publication.publishRequestId()) + .setDerivedWorkflowIdentity(publication.derivedWorkflowIdentity()) + .setRequestDigest(publication.requestDigest()) + .setSourceReadBinding(ByteString.copyFrom(bindingBytes)) + .setSourceReadBindingDigest(binding.digest()) + .build(); + requireWireSize(request.getSerializedSize()); + return request; + } + + /** Validates the unchanged publication request fields and reconstructs the exact binding. */ + public static GameLogicPublicationSourceReadBinding fromRequest( + GetDraftDesignDigestRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize(request.getSerializedSize()); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown publication digest request fields"); + } + requireBindingSize(request.getSourceReadBinding().size()); + if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID + || !request.getBaseVersionId().isEmpty()) { + throw new IllegalArgumentException("Only full-version publication reads are supported"); + } + + PublicationDigestRequestBinding publication = + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + request.getTenantId(), + request.getVersionId(), + request.getBaseVersionId(), + "", + request.getPublishRequestId()); + publication.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); + GameLogicPublicationSourceReadBinding binding = + GameLogicPublicationSourceReadBinding.fromStored( + publication, request.getSourceReadBinding().toByteArray()); + if (!binding.digest().equals(request.getSourceReadBindingDigest())) { + throw new IllegalArgumentException("Changed publication source-read binding digest"); + } + return binding; + } + + /** + * Encodes an owner-readback terminal. The caller must supply the genuine terminal returned by its + * Game Logic owner read; this codec verifies its retained content correlation but cannot + * establish storage provenance by inspecting a value. + */ + public static GetDraftDesignDigestResponse toResponse( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal genuineTerminal) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(genuineTerminal, "genuineTerminal"); + requireFullVersion(binding); + requireExactRetainedTerminal(binding, genuineTerminal, null); + + byte[] bindingBytes = binding.canonicalBytes(); + byte[] terminalBytes = genuineTerminal.canonicalBytes(); + requireBindingSize(bindingBytes.length); + requireTerminalSize(terminalBytes.length); + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + byte[] manifestBytes = genuineTerminal.manifestBytes(); + String manifestDigest = GameplayRuleManifest.sha256(manifestBytes); + String abilitySchemaDigest = + GameplayAbilitySchemaProjection.digest(authorization.source().manifest()); + String tenantId = binding.publicationRequest().tenantId(); + String versionId = binding.publicationRequest().versionId(); + String commitId = authorization.source().binding().commitId().toString(); + String terminalDigest = genuineTerminal.digest(); + + int expectedWireSize = + stringFieldSize(1, tenantId) + + stringFieldSize(3, commitId) + + stringFieldSize(4, manifestDigest) + + CodedOutputStream.computeInt32Size(5, DIGEST_SCHEMA_VERSION) + + stringFieldSize(7, versionId) + + bytesFieldSize(10, bindingBytes.length) + + stringFieldSize(11, binding.digest()) + + bytesFieldSize(12, terminalBytes.length) + + stringFieldSize(13, terminalDigest) + + stringFieldSize(14, abilitySchemaDigest) + + stringFieldSize(15, CANONICALIZATION); + requireWireSize(expectedWireSize); + + GetDraftDesignDigestResponse response = + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(tenantId) + .setAppliedCommitId(commitId) + .setContentDigest(manifestDigest) + .setDigestSchemaVersion(DIGEST_SCHEMA_VERSION) + .setVersionId(versionId) + .setBaseVersionId("") + .setSourceReadBinding(ByteString.copyFrom(bindingBytes)) + .setSourceReadBindingDigest(binding.digest()) + .setRetainedIntakeTerminal(ByteString.copyFrom(terminalBytes)) + .setRetainedIntakeTerminalDigest(terminalDigest) + .setAbilitySchemaDigest(abilitySchemaDigest) + .setCanonicalization(CANONICALIZATION) + .build(); + requireWireSize(response.getSerializedSize()); + return response; + } + + /** + * Decodes exact selection and retained-content evidence without authenticating its producer. For + * an authenticated caller namespace check, use the three-argument overload. + */ + public static Evidence fromResponse( + GameLogicPublicationSourceReadBinding expectedBinding, + GetDraftDesignDigestResponse response) { + return decodeResponse(expectedBinding, response, null); + } + + /** Decodes the response while also enforcing the caller's configured GL namespace. */ + public static Evidence fromResponse( + GameLogicPublicationSourceReadBinding expectedBinding, + GetDraftDesignDigestResponse response, + String expectedNamespace) { + Objects.requireNonNull(expectedNamespace, "expectedNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(expectedNamespace)) { + throw new IllegalArgumentException("Canonical expected Game Logic namespace required"); + } + return decodeResponse(expectedBinding, response, expectedNamespace); + } + + private static Evidence decodeResponse( + GameLogicPublicationSourceReadBinding expectedBinding, + GetDraftDesignDigestResponse response, + String expectedNamespace) { + Objects.requireNonNull(expectedBinding, "expectedBinding"); + Objects.requireNonNull(response, "response"); + requireFullVersion(expectedBinding); + requireWireSize(response.getSerializedSize()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown publication digest response fields"); + } + rejectNonemptyError(response); + requireBindingSize(response.getSourceReadBinding().size()); + requireTerminalSize(response.getRetainedIntakeTerminal().size()); + requireResponseScope(expectedBinding, response); + requireExactBindingEcho(expectedBinding, response); + + GameLogicGameplayRuleIntakeTerminal terminal = + GameLogicGameplayRuleIntakeTerminal.fromStored( + response.getRetainedIntakeTerminal().toByteArray()); + requireExactRetainedTerminal(expectedBinding, terminal, expectedNamespace); + String terminalDigest = terminal.digest(); + if (!terminalDigest.equals(response.getRetainedIntakeTerminalDigest())) { + throw new IllegalArgumentException("Changed retained intake terminal digest"); + } + + byte[] manifestBytes = terminal.manifestBytes(); + String manifestDigest = GameplayRuleManifest.sha256(manifestBytes); + String abilitySchemaDigest = + GameplayAbilitySchemaProjection.digest(expectedBinding.authorization().source().manifest()); + if (!manifestDigest.equals(response.getContentDigest()) + || !abilitySchemaDigest.equals(response.getAbilitySchemaDigest()) + || response.getDigestSchemaVersion() != DIGEST_SCHEMA_VERSION + || !CANONICALIZATION.equals(response.getCanonicalization())) { + throw new IllegalArgumentException("Changed retained publication digest evidence"); + } + + return new Evidence( + expectedBinding, + terminal, + manifestDigest, + abilitySchemaDigest, + DIGEST_SCHEMA_VERSION, + CANONICALIZATION); + } + + private static void requireResponseScope( + GameLogicPublicationSourceReadBinding binding, GetDraftDesignDigestResponse response) { + PublicationDigestRequestBinding publication = binding.publicationRequest(); + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + String selectedVersionRowId = + Long.toString(authorization.source().binding().target().gameDesignVersionRowId()); + if (response.getScopeCase() != GetDraftDesignDigestResponse.ScopeCase.VERSION_ID + || !response.getBaseVersionId().isEmpty() + || !publication.tenantId().equals(response.getTenantId()) + || !authorization.tenantId().toString().equals(response.getTenantId()) + || !publication.versionId().equals(response.getVersionId()) + || !selectedVersionRowId.equals(response.getVersionId()) + || !authorization + .source() + .binding() + .commitId() + .toString() + .equals(response.getAppliedCommitId())) { + throw new IllegalArgumentException("Changed typed publication source scope"); + } + } + + private static void requireExactBindingEcho( + GameLogicPublicationSourceReadBinding binding, GetDraftDesignDigestResponse response) { + if (!binding.digest().equals(response.getSourceReadBindingDigest())) { + throw new IllegalArgumentException("Changed publication source-read binding digest"); + } + byte[] expectedBytes = binding.canonicalBytes(); + byte[] suppliedBytes = response.getSourceReadBinding().toByteArray(); + if (!Arrays.equals(expectedBytes, suppliedBytes)) { + throw new IllegalArgumentException("Substituted publication source-read binding"); + } + } + + private static void requireExactRetainedTerminal( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal, + String expectedNamespace) { + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + if (terminal.outcome() != GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED + || !Arrays.equals(authorization.canonicalBytes(), terminal.authorizationBytes()) + || !Arrays.equals( + authorization.canonicalBytes(), terminal.operation().authorization().canonicalBytes()) + || !Arrays.equals( + authorization.source().canonicalBytes(), terminal.selectedSourceBytes())) { + throw new IllegalArgumentException( + "Terminal is not the exact retained source for this publication binding"); + } + if (expectedNamespace != null + && !expectedNamespace.equals(terminal.operation().targetNamespace())) { + throw new IllegalArgumentException("Retained terminal namespace differs from caller scope"); + } + } + + private static void requireFullVersion(GameLogicPublicationSourceReadBinding binding) { + if (binding.publicationRequest().scopeKind() + != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException("Only full-version publication reads are supported"); + } + } + + private static void rejectNonemptyError(GetDraftDesignDigestResponse response) { + if (!response.hasError()) return; + var error = response.getError(); + if (!error.getUnknownFields().asMap().isEmpty() + || !error.getCode().isEmpty() + || !error.getMessage().isEmpty()) { + throw new IllegalArgumentException("Publication digest response carries an error"); + } + } + + private static int stringFieldSize(int fieldNumber, String value) { + return CodedOutputStream.computeStringSize(fieldNumber, value); + } + + private static int bytesFieldSize(int fieldNumber, int length) { + return CodedOutputStream.computeTagSize(fieldNumber) + + CodedOutputStream.computeUInt32SizeNoTag(length) + + length; + } + + private static void requireBindingSize(int length) { + if (length <= 0 || length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Invalid publication source-read binding size"); + } + } + + private static void requireTerminalSize(int length) { + if (length <= 0 || length > MAX_TERMINAL_BYTES) { + throw new IllegalArgumentException("Invalid retained intake terminal size"); + } + } + + private static void requireWireSize(int size) { + if (size < 0 || size > MAX_WIRE_BYTES) { + throw new IllegalArgumentException("Publication digest protobuf exceeds 24 MiB"); + } + } + + /** Closed immutable value containing exact retained-source and derived digest evidence. */ + public record Evidence( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal, + String manifestDigest, + String abilitySchemaDigest, + int digestSchemaVersion, + String canonicalization) { + public Evidence { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(terminal, "terminal"); + Objects.requireNonNull(manifestDigest, "manifestDigest"); + Objects.requireNonNull(abilitySchemaDigest, "abilitySchemaDigest"); + Objects.requireNonNull(canonicalization, "canonicalization"); + requireFullVersion(binding); + requireExactRetainedTerminal(binding, terminal, null); + if (digestSchemaVersion != DIGEST_SCHEMA_VERSION + || !CANONICALIZATION.equals(canonicalization) + || !GameplayRuleManifest.sha256(terminal.manifestBytes()).equals(manifestDigest) + || !GameplayAbilitySchemaProjection.digest(binding.authorization().source().manifest()) + .equals(abilitySchemaDigest)) { + throw new IllegalArgumentException("Invalid retained publication digest evidence"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java new file mode 100644 index 0000000000..be45aefd79 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.AdmissionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Command; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Condition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ContinuousOverlay; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DefaultBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Effect; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectOperation; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ObservationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Predicate; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Resource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.StatField; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetSet; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetingPolicy; + +/** + * Content-only projection; the caller must independently prove exact retained source provenance. + */ +public final class GameplayAbilitySchemaProjection { + public static final String SCHEMA = "gameplay-ability-schema/v1"; + + private GameplayAbilitySchemaProjection() {} + + public static String canonicalJson(GameplayRuleManifest source) { + // Validate every family, including definitions that will not occur in the projection. + var complete = new GameplayRuleManifest(Objects.requireNonNull(source).families()); + Map definitions = new HashMap<>(); + complete + .families() + .forEach( + (family, values) -> + values.forEach(value -> definitions.put(new Key(family, value.key()), value))); + var pending = new ArrayDeque(); + for (Family root : List.of(Family.ABILITIES, Family.ACTIONS)) + complete.families().get(root).forEach(value -> pending.add(new Key(root, value.key()))); + Set visited = new HashSet<>(); + while (!pending.isEmpty()) { + Key key = pending.remove(); + if (!visited.add(key)) continue; + Definition value = definitions.get(key); + if (value == null) throw new IllegalArgumentException("Unresolved ability-schema reference"); + dependencies(value, definitions, pending); + } + Map> retained = new EnumMap<>(Family.class); + complete + .families() + .forEach( + (family, values) -> + retained.put( + family, + values.stream() + .filter(value -> visited.contains(new Key(family, value.key()))) + .toList())); + // Closure must itself remain a complete, valid inventory; do not repair missing edges with + // defaults. + var projection = new GameplayRuleManifest(retained); + Map families = new LinkedHashMap<>(); + for (Family family : Family.values()) + families.put(family.name(), projection.families().get(family)); + return GameplayRuleManifest.canonical(Map.of("schema", SCHEMA, "families", families)); + } + + public static byte[] canonicalBytes(GameplayRuleManifest source) { + return canonicalJson(source).getBytes(StandardCharsets.UTF_8); + } + + public static String digest(GameplayRuleManifest source) { + return GameplayRuleManifest.sha256(canonicalBytes(source)); + } + + private record Key(Family family, String key) {} + + private static void add(ArrayDeque pending, Family family, String key) { + pending.add(new Key(family, key)); + } + + private static void addAll(ArrayDeque pending, Family family, List keys) { + keys.forEach(key -> add(pending, family, key)); + } + + private static void numeric( + ArrayDeque pending, Map definitions, String key) { + // The closed grammar rejects cross-family stat/resource collisions before traversal. + add( + pending, + definitions.containsKey(new Key(Family.RESOURCES, key)) ? Family.RESOURCES : Family.STATS, + key); + } + + private static void targets(ArrayDeque pending, List targets) { + for (TargetSet target : targets) { + add(pending, Family.TARGETING_POLICIES, target.targetingPolicyKey()); + add(pending, Family.SELECTION_POLICIES, target.targetSelectionPolicyKey()); + if (target.unresolvedFeedbackKey() != null) + add(pending, Family.FEEDBACK, target.unresolvedFeedbackKey()); + } + } + + private static void predicate( + ArrayDeque pending, Map definitions, Predicate value) { + switch (value.kind()) { + case STAT_COMPARE -> numeric(pending, definitions, value.factKey()); + case CONDITION_PRESENT -> add(pending, Family.CONDITIONS, value.factKey()); + case DISPOSITION_EQUALS -> add(pending, Family.DISPOSITIONS, value.factKey()); + case TRUE, FALSE, ALL, ANY, NOT -> {} + } + for (Predicate operand : value.operands()) predicate(pending, definitions, operand); + } + + private static void dependencies( + Definition definition, Map definitions, ArrayDeque pending) { + switch (definition) { + case Stat ignored -> {} + case Resource ignored -> {} + case AdmissionTag ignored -> {} + case Feedback ignored -> {} + case Ability value -> add(pending, Family.ACTIONS, value.actionSequenceId()); + case Condition value -> addAll(pending, Family.EFFECTS, value.effectKeys()); + case Effect value -> { + if (value.statKey() != null) { + if (value.operation() == EffectOperation.ADJUST_RESOURCE + || value.statField() == StatField.MAXIMUM) + add(pending, Family.RESOURCES, value.statKey()); + else numeric(pending, definitions, value.statKey()); + } + if (value.conditionKey() != null) add(pending, Family.CONDITIONS, value.conditionKey()); + } + case Action value -> { + addAll(pending, Family.ADMISSION_TAGS, value.admissionTags()); + targets(pending, value.targetSets()); + value.costs().forEach(cost -> add(pending, Family.RESOURCES, cost.statKey())); + value.effects().forEach(effect -> add(pending, Family.EFFECTS, effect.effectKey())); + addAll(pending, Family.FEEDBACK, value.feedbackKeys()); + } + case Command value -> { + add(pending, Family.ACTIONS, value.actionSequenceId()); + addAll(pending, Family.ADMISSION_TAGS, value.admissionTags()); + } + case Disposition value -> { + addAll(pending, Family.ADMISSION_TAGS, value.deniedAdmissionTags()); + add(pending, Family.FEEDBACK, value.safeFeedbackKey()); + } + case ContinuousOverlay value -> { + predicate(pending, definitions, value.eligibleWhen()); + addAll(pending, Family.ADMISSION_TAGS, value.deniedAdmissionTags()); + addAll(pending, Family.EFFECTS, value.effectKeys()); + } + case ObservationPolicy value -> predicate(pending, definitions, value.observableWhen()); + case TargetingPolicy value -> { + add(pending, Family.OBSERVATION_POLICIES, value.observationPolicyKey()); + predicate(pending, definitions, value.eligibleWhen()); + add(pending, Family.FEEDBACK, value.safeFailureFeedbackKey()); + } + case SelectionPolicy value -> + value + .comparators() + .forEach( + comparator -> { + if (comparator.statField() == StatField.MAXIMUM) + add(pending, Family.RESOURCES, comparator.statKey()); + else numeric(pending, definitions, comparator.statKey()); + }); + case DefaultBinding value -> targets(pending, value.targetSets()); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java new file mode 100644 index 0000000000..fbcc6e9844 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignGameplayRuleSourceReadServiceGrpc; + +/** Explicit file-backed mTLS client for the exact same-namespace GD source read. */ +public final class GameplayRuleSourceReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameplayRuleSourceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameplayRuleSourceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Game Design complete gameplay source read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Game Design complete gameplay source read stub unavailable"); + initialized = true; + } + + /** Returns exact source evidence only after Game Design server mTLS identity verification. */ + public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("GD source transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedGameplayRuleSource(GameplayRuleSourceReadGrpcCodec.toRequest(request)); + try { + return GameplayRuleSourceReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid complete source evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignGameplayRuleSourceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design complete gameplay source read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read " + + label + + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java new file mode 100644 index 0000000000..a4bdda852f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact authenticated GD complete-source read; never a mutation authorization. */ +public record GameplayRuleSourceReadEvidence(Request request, GameplayRuleSelectedSource source) { + public GameplayRuleSourceReadEvidence { + Objects.requireNonNull(request); + Objects.requireNonNull(source); + if (!request.binding().equals(source.binding())) + throw new IllegalArgumentException("GD source differs from selected complete binding"); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + DraftCommitBinding binding, + Proof proof, + String purpose) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported source schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + Objects.requireNonNull(proof); + if (!GameLogicIntakeSourceReadScope.PURPOSE.equals(purpose) + || !binding.equals(proof.selected())) + throw new IllegalArgumentException("Exact source proof and closed purpose required"); + if (proof instanceof Preliminary preliminary + && !targetNamespace.equals(preliminary.scope().targetNamespace())) + throw new IllegalArgumentException("Source proof namespace differs"); + if (readRequestId.equals(binding.requestId()) || readRequestId.equals(binding.commitId())) + throw new IllegalArgumentException("Separate source read correlation required"); + if (readRequestId.equals(proof.operationId()) + || readRequestId.equals(proof.intakeRequestId()) + || readRequestId.equals(proof.fenceId())) + throw new IllegalArgumentException("Separate intake read correlation required"); + } + + public static Request forAccountSourceScope( + String namespace, GameLogicIntakeSourceReadScope scope) { + return new Request( + 1, + namespace, + UUID.randomUUID(), + scope.selected(), + new Preliminary(scope), + GameLogicIntakeSourceReadScope.PURPOSE); + } + + public static Request forFinalizedIntake( + String namespace, GameLogicIntakeAuthorizationBinding authorization) { + return new Request( + 1, + namespace, + UUID.randomUUID(), + authorization.source().binding(), + new Finalized(authorization), + GameLogicIntakeSourceReadScope.PURPOSE); + } + } + + public sealed interface Proof permits Preliminary, Finalized { + DraftCommitBinding selected(); + + byte[] canonicalBytes(); + + String digest(); + + UUID operationId(); + + UUID fenceId(); + + UUID intakeRequestId(); + } + + public record Preliminary(GameLogicIntakeSourceReadScope scope) implements Proof { + public Preliminary { + Objects.requireNonNull(scope); + } + + public DraftCommitBinding selected() { + return scope.selected(); + } + + public byte[] canonicalBytes() { + return scope.canonicalBytes(); + } + + public String digest() { + return scope.digest(); + } + + public UUID operationId() { + return scope.operationId(); + } + + public UUID fenceId() { + return scope.fenceId(); + } + + public UUID intakeRequestId() { + return scope.intakeRequestId(); + } + } + + public record Finalized(GameLogicIntakeAuthorizationBinding authorization) implements Proof { + public Finalized { + Objects.requireNonNull(authorization); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof Finalized finalized + && java.util.Arrays.equals(canonicalBytes(), finalized.canonicalBytes())); + } + + @Override + public int hashCode() { + return java.util.Arrays.hashCode(canonicalBytes()); + } + + public DraftCommitBinding selected() { + return authorization.source().binding(); + } + + public byte[] canonicalBytes() { + return authorization.canonicalBytes(); + } + + public String digest() { + return authorization.digest(); + } + + public UUID operationId() { + return authorization.operationId(); + } + + public UUID fenceId() { + return authorization.fenceId(); + } + + public UUID intakeRequestId() { + return authorization.intakeRequestId(); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java new file mode 100644 index 0000000000..e21ee2c692 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse; + +/** Closed wire and exact request/source correlation. Decode only after peer authentication. */ +public final class GameplayRuleSourceReadGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private GameplayRuleSourceReadGrpcCodec() {} + + public static ReadSelectedGameplayRuleSourceRequest toRequest( + GameplayRuleSourceReadEvidence.Request value) { + var builder = + ReadSelectedGameplayRuleSourceRequest.newBuilder() + .setSchemaVersion(value.schemaVersion()) + .setTargetNamespace(value.targetNamespace()) + .setReadRequestId(value.readRequestId().toString()) + .setGameDesignBindingJson(value.binding().canonicalJson()) + .setGameDesignBindingDigest(value.binding().digest()) + .setPurpose(value.purpose()) + .setAuthorizationProofDigest(value.proof().digest()); + var bytes = com.google.protobuf.ByteString.copyFrom(value.proof().canonicalBytes()); + if (value.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary) + builder.setPreliminarySourceScope(bytes); + else builder.setFinalizedIntakeAuthorization(bytes); + var wire = builder.build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized GD source request"); + return wire; + } + + public static GameplayRuleSourceReadEvidence.Request fromRequest( + ReadSelectedGameplayRuleSourceRequest value) { + if (value == null + || value.getSerializedSize() > MAX_WIRE_BYTES + || !value.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Unknown source fields"); + DraftAuthorizationFenceBinding.canonicalUuid(value.getReadRequestId()); + GameplayRuleSourceReadEvidence.Proof proof = + switch (value.getAuthorizationProofCase()) { + case PRELIMINARY_SOURCE_SCOPE -> + new GameplayRuleSourceReadEvidence.Preliminary( + GameLogicIntakeSourceReadScope.fromStored( + value.getPreliminarySourceScope().toByteArray())); + case FINALIZED_INTAKE_AUTHORIZATION -> + new GameplayRuleSourceReadEvidence.Finalized( + GameLogicIntakeAuthorizationBinding.fromStored( + value.getFinalizedIntakeAuthorization().toByteArray())); + default -> throw new IllegalArgumentException("Source permission proof required"); + }; + if (!proof.digest().equals(value.getAuthorizationProofDigest())) + throw new IllegalArgumentException("Changed source proof digest"); + return new GameplayRuleSourceReadEvidence.Request( + value.getSchemaVersion(), + value.getTargetNamespace(), + UUID.fromString(value.getReadRequestId()), + DraftCommitBinding.fromStored( + value.getGameDesignBindingJson(), value.getGameDesignBindingDigest()), + proof, + value.getPurpose()); + } + + public static ReadSelectedGameplayRuleSourceResponse toResponse( + GameplayRuleSourceReadEvidence evidence) { + var wire = + ReadSelectedGameplayRuleSourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCompleteSourceSnapshotJson(evidence.source().snapshotJson()) + .setCompleteSourceSnapshotDigest(evidence.source().digest()) + .build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized GD source response"); + return wire; + } + + public static GameplayRuleSourceReadEvidence fromResponse( + GameplayRuleSourceReadEvidence.Request request, + ReadSelectedGameplayRuleSourceResponse response) { + if (response == null + || response.getSerializedSize() > MAX_WIRE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest())) + throw new IllegalArgumentException("Changed source read correlation"); + var source = new GameplayRuleSelectedSource(response.getCompleteSourceSnapshotJson()); + if (!source.digest().equals(response.getCompleteSourceSnapshotDigest())) + throw new IllegalArgumentException("Changed source digest"); + return new GameplayRuleSourceReadEvidence(request, source); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java new file mode 100644 index 0000000000..fc62e0ae82 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit file-backed mTLS client for the exact same-namespace Account settlement read. */ +public final class GrpcAccountGameLogicIntakeSettlementReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceBlockingStub> + implements AccountGameLogicIntakeSettlementReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAccountGameLogicIntakeSettlementReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAccountGameLogicIntakeSettlementReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account intake settlement read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account intake settlement read stub unavailable"); + initialized = true; + } + + /** + * Returns a validated immutable settlement receipt after exact Account server mTLS verification. + */ + @Override + public AccountGameLogicIntakeSettlementReadEvidence read( + AccountGameLogicIntakeSettlementReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Account settlement transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account intake settlement read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleGameLogicIntake(AccountGameLogicIntakeSettlementProtoCodec.toRequest(request)); + try { + return AccountGameLogicIntakeSettlementProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account returned invalid settlement evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeSettlementServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account intake settlement read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account intake settlement read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account intake settlement read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account intake settlement read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account intake settlement read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account intake settlement read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java new file mode 100644 index 0000000000..70caa14ab4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for the standalone, unregistered Account intake producer. */ +public final class GrpcGameLogicIntakeAuthorizationClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceBlockingStub> + implements GameLogicIntakeAuthorizationClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcGameLogicIntakeAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcGameLogicIntakeAuthorizationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Canonical workload namespace required"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account intake authorization client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account intake authorization stub unavailable"); + initialized = true; + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result authorize( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + return invoke(request, originalCreatorCredential, Operation.AUTHORIZE); + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result recover( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + return invoke(request, originalCreatorCredential, Operation.RECOVER); + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result abort( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + return invoke(request, originalCreatorCredential, Operation.ABORT); + } + + private GameLogicIntakeAuthorizationEvidence.Result invoke( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential, + Operation operation) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Account intake authorization requires no ambient SQL"); + Objects.requireNonNull(request); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account intake authorization namespace mismatch"); + var current = stub(); + if (closed || !initialized || current == null) + throw new IllegalStateException("Account intake authorization client unavailable"); + try { + var secured = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"), + credentials(originalCreatorCredential, operation))) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); + var response = + switch (operation) { + case AUTHORIZE -> secured.authorizeIntake(wireRequest); + case RECOVER -> secured.recoverIntake(wireRequest); + case ABORT -> secured.abortIntake(wireRequest); + }; + var result = GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, response); + if (operation == Operation.AUTHORIZE + && result.outcome() != GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED) + throw new IllegalArgumentException("Authorization response was not finalized"); + return result; + } catch (StatusRuntimeException unavailable) { + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account Game Logic intake authorization denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid Game Logic intake authorization evidence"); + } + } + + private static io.grpc.CallCredentials credentials( + String originalCreatorCredential, Operation operation) { + return switch (operation) { + case AUTHORIZE -> + AccountGameLogicIntakeAuthorizationCredentials.forAuthorize(originalCreatorCredential); + case RECOVER -> + AccountGameLogicIntakeAuthorizationCredentials.forRecover(originalCreatorCredential); + case ABORT -> + AccountGameLogicIntakeAuthorizationCredentials.forAbort(originalCreatorCredential); + }; + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeAuthorizationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException("Account intake authorization requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) + throw new IllegalArgumentException( + "Account intake authorization requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid Account intake authorization " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account intake authorization " + label + " must be an existing readable file"); + } + + private enum Operation { + AUTHORIZE, + RECOVER, + ABORT + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java new file mode 100644 index 0000000000..6ec08f5c07 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; + +/** File-backed mTLS client for the unregistered selected-source retain transport. */ +public final class GrpcGameLogicIntakeRetainClient + extends AbstractReloadingBlockingGrpcClient< + GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub> + implements GameLogicIntakeRetainClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcGameLogicIntakeRetainClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcGameLogicIntakeRetainClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Game Logic intake retain client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Logic intake retain stub unavailable"); + } + initialized = true; + } + + @Override + public GameLogicIntakeRetainEvidence retain(GameLogicIntakeRetainEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) { + throw new IllegalStateException("Game Logic intake retain transport must run outside SQL"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Logic intake retain must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .retainGameplayRuleIntake(GameLogicIntakeRetainProtoCodec.toRequest(request)); + try { + return GameLogicIntakeRetainProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Logic returned invalid intake retain evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameLogicService(); + } + + @Override + protected String defaultTarget() { + return "game-logic-service:6565"; + } + + @Override + protected GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service"; + return GameLogicGameplayRuleIntakeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Logic intake retain client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Game Logic intake retain requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Logic intake retain requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Logic intake retain requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Logic intake retain " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Logic intake retain " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java new file mode 100644 index 0000000000..910b480dc7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit file-backed mTLS client for same-namespace Account source permission confirmation. */ +public final class GrpcGameLogicIntakeSourceReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceBlockingStub> + implements GameLogicIntakeSourceReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcGameLogicIntakeSourceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcGameLogicIntakeSourceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Account GL intake authorization read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account GL intake authorization read stub unavailable"); + initialized = true; + } + + /** + * Returns exact source permission confirmation after Account server mTLS identity verification. + */ + public GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Account intake transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account GL intake authorization read must use the configured workload namespace"); + } + var stub = requireStub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); + var response = + request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary + ? stub.readSourceScope(wire) + : stub.readFinalizedIntake(wire); + try { + return GameLogicIntakeSourceReadProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid source permission evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeSourceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account GL intake authorization read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java new file mode 100644 index 0000000000..fa86e95a08 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -0,0 +1,711 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Structural and actual loopback-mTLS proof for the closed Account settlement transport. */ +class AccountGameLogicIntakeSettlementReadGrpcTest { + private static final String NAMESPACE = "test"; + private static final String GL_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final int LARGE_SOURCE_ENTRIES = 1800; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GrpcAccountGameLogicIntakeSettlementReadClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void roundTripsExactReceiptsAndNewCorrelationRetries() { + for (var outcome : Outcome.values()) { + var evidence = evidence("test", 1, outcome); + var originalBytes = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + originalBytes, "account-game-logic-intake-settlement/v1"); + DraftAuthorizationFenceBinding.frame( + originalBytes, evidence.receipt().terminal().canonicalBytes()); + assertThat(evidence.receipt().canonicalBytes()).isEqualTo(originalBytes.toByteArray()); + var request = + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request())); + assertThat(request).isEqualTo(evidence.request()); + assertThat(request.hashCode()).isEqualTo(evidence.request().hashCode()); + var wire = AccountGameLogicIntakeSettlementProtoCodec.toResponse(evidence); + assertThat( + AccountGameLogicIntakeSettlementProtoCodec.fromResponse(request, wire) + .receipt() + .canonicalBytes()) + .isEqualTo(evidence.receipt().canonicalBytes()); + var retry = + AccountGameLogicIntakeSettlementReadEvidence.Request.create("test", request.binding()); + var replay = new AccountGameLogicIntakeSettlementReadEvidence(retry, evidence.receipt()); + assertThat( + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + retry, AccountGameLogicIntakeSettlementProtoCodec.toResponse(replay)) + .receipt() + .digest()) + .isEqualTo(evidence.receipt().digest()); + assertThatThrownBy(() -> AccountGameLogicIntakeSettlementProtoCodec.fromResponse(retry, wire)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEvidenceOversizeTrailingAndNoncanonicalReceipts() { + var evidence = evidence("test", 1, Outcome.RETAINED); + var wire = AccountGameLogicIntakeSettlementProtoCodec.toResponse(evidence); + var changed = evidence("test", 1, Outcome.RETAINED); + assertThatThrownBy( + () -> + new AccountGameLogicIntakeSettlementReadEvidence( + evidence.request(), changed.receipt())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "other", evidence.request().binding()), + evidence.receipt())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setSettlementReceiptDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setTargetNamespace("other")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setOriginalSettlementReceipt( + ByteString.copyFrom(changed.receipt().canonicalBytes())) + .setSettlementReceiptDigest(changed.receipt().digest()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder().setIntakeAuthorizationDigest("changed").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder() + .setOriginalIntakeAuthorization(ByteString.copyFrom(new byte[4194305])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + byte[] trailing = + java.util.Arrays.copyOf( + evidence.receipt().canonicalBytes(), evidence.receipt().canonicalBytes().length + 1); + assertThatThrownBy(() -> AccountGameLogicIntakeSettlementEvidence.fromStored(trailing)) + .isInstanceOf(IllegalArgumentException.class); + byte[] wrongSchema = evidence.receipt().canonicalBytes(); + wrongSchema[Integer.BYTES] ^= 1; + assertThatThrownBy(() -> AccountGameLogicIntakeSettlementEvidence.fromStored(wrongSchema)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setOriginalSettlementReceipt( + ByteString.copyFrom( + new byte + [AccountGameLogicIntakeSettlementEvidence.MAX_CANONICAL_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse + .getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresFileBackedMtlsConfiguredNamespaceAndNoAmbientSql() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + client = + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, + pki.clientProperties(tempDirectory, pki.accountClient()), + new GrpcChannelFactory(), + NAMESPACE); + var evidence = evidence("test", 1, Outcome.ABORTED); + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + client.read( + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "other", evidence.request().binding()))) + .isInstanceOf(IllegalArgumentException.class); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside SQL"); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside SQL"); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + client.close(); + assertThatThrownBy(() -> client.init()).isInstanceOf(IllegalStateException.class); + } + + @Test + void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispatch() + throws Exception { + var large = evidence("test", LARGE_SOURCE_ENTRIES, Outcome.RETAINED); + assertThat(large.receipt().canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); + startServer(pki.gameLogicServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + var actual = client.read(large.request()); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(large.receipt().canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + startServer(pki.wrongServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(large.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + private enum Outcome { + RETAINED, + ABORTED + } + + private void startServer( + TestIdentity identity, AccountGameLogicIntakeSettlementReadEvidence evidence) + throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceImplBase() { + @Override + public void settleGameLogicIntake( + SettleGameLogicIntakeRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = AccountGameLogicIntakeSettlementProtoCodec.fromRequest(wire); + var response = + AccountGameLogicIntakeSettlementProtoCodec.toResponse( + new AccountGameLogicIntakeSettlementReadEvidence(request, evidence.receipt())); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcAccountGameLogicIntakeSettlementReadClient newClient( + Server target, TestIdentity local) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + target.getPort()); + return new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ + private static AccountGameLogicIntakeSettlementReadEvidence evidence( + String namespace, int entryCount, Outcome outcome) { + var tenant = UUID.randomUUID(); + var version = UUID.randomUUID(); + var requestId = UUID.randomUUID(); + var commitId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var definitionsByFamily = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + definitionsByFamily.put(family, new ArrayList<>()); + definitionsByFamily.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(definitionsByFamily); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountEvidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.fromString(accountEvidence.scopeId()), + source, + List.of(accountEvidence)); + var operation = new GameLogicGameplayRuleIntakeOperation(namespace, authorization); + var terminal = + outcome == Outcome.RETAINED + ? GameLogicGameplayRuleIntakeTerminal.retained( + operation, + source.canonicalBytes(), + manifest.canonicalJson().getBytes(StandardCharsets.UTF_8)) + : GameLogicGameplayRuleIntakeTerminal.aborted(operation); + return new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization), + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java new file mode 100644 index 0000000000..d63824aaca --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java @@ -0,0 +1,277 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class GameLogicIntakeAuthorizationGrpcCodecTest { + private static final String CREDENTIAL = "unchanged.creator.secret"; + + @Test + void roundTripsExactSelectionAndAllRecoveryPhasesWithoutCredentialInWire() { + var request = request(); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); + assertThat(GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wireRequest).selected()) + .isEqualTo(request.selected()); + var credentialBytes = CREDENTIAL.getBytes(java.nio.charset.StandardCharsets.UTF_8); + assertThat(containsSequence(wireRequest.toByteArray(), credentialBytes)).isFalse(); + + var finalized = authorization(request); + var finalizedResult = + GameLogicIntakeAuthorizationEvidence.Result.authorized(request, finalized); + var finalizedWire = GameLogicIntakeAuthorizationGrpcCodec.toResponse(finalizedResult); + var decoded = GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, finalizedWire); + assertThat(decoded.outcome()).isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); + assertThat(decoded.authorization().orElseThrow().canonicalBytes()) + .containsExactly(finalized.canonicalBytes()); + assertThat(containsSequence(finalizedWire.toByteArray(), credentialBytes)).isFalse(); + + var scope = scope(request); + for (var outcome : + List.of( + GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED, + GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED)) { + var result = + new GameLogicIntakeAuthorizationEvidence.Result( + request, outcome, Optional.of(scope), Optional.empty()); + var response = GameLogicIntakeAuthorizationGrpcCodec.toResponse(result); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, response).sourceScope()) + .contains(scope); + } + var finalizedRecovery = + new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED, + Optional.of(scope), + Optional.of(authorization(scope))); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, GameLogicIntakeAuthorizationGrpcCodec.toResponse(finalizedRecovery)) + .sourceScope()) + .contains(scope); + } + + @Test + void rejectsUnknownChangedAndNoncanonicalEvidenceAndCredentialInputs() { + var request = request(); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); + var response = + GameLogicIntakeAuthorizationGrpcCodec.toResponse( + GameLogicIntakeAuthorizationEvidence.Result.authorized( + request, authorization(request))); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setTransportRequestId(UUID.randomUUID().toString()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setSelectedDraftBinding(ByteString.copyFromUtf8("{}")) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, response.toBuilder().setOutcomeValue(99).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte + [GameLogicIntakeAuthorizationEvidence.MAX_SELECTION_BYTES + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeAuthorizationCredentials.Credential.of("contains whitespace")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED, + Optional.of(scope(request)), + Optional.of(authorization(request)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsResponsesOverTheExplicitTwentyFourMiBWireBudget() { + var request = request(); + var response = + GameLogicIntakeAuthorizationGrpcCodec.toResponse( + GameLogicIntakeAuthorizationEvidence.Result.authorized( + request, authorization(request))); + var oversized = + response.toBuilder() + .setRequest( + GameLogicIntakeAuthorizationGrpcCodec.toRequest(request).toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte[GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES])) + .build()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + static GameLogicIntakeAuthorizationEvidence.Request request() { + return GameLogicIntakeAuthorizationEvidence.Request.create( + "test", UUID.randomUUID(), selected()); + } + + static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeAuthorizationEvidence.Request request) { + return authorization(scope(request)); + } + + static GameLogicIntakeAuthorizationBinding authorization(GameLogicIntakeSourceReadScope scope) { + var selected = scope.selected(); + UUID actor = scope.actorAccountId(); + var source = source(selected); + return new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + "0", + "revisionId", + binding.revisions().getFirst().revisionId().toString()))))); + } + + static GameLogicIntakeSourceReadScope scope( + GameLogicIntakeAuthorizationEvidence.Request request) { + return new GameLogicIntakeSourceReadScope( + request.targetNamespace(), + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + UUID.randomUUID(), + request.selected(), + "spiffe://firemud/ns/" + request.targetNamespace() + "/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + } + + private static boolean containsSequence(byte[] bytes, byte[] sequence) { + for (int start = 0; start <= bytes.length - sequence.length; start++) { + int index = 0; + while (index < sequence.length && bytes[start + index] == sequence[index]) index++; + if (index == sequence.length) return true; + } + return false; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java new file mode 100644 index 0000000000..94026f43f9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java @@ -0,0 +1,384 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.junit.jupiter.api.Test; + +class GameLogicIntakeRetainProtoCodecTest { + private static final String NAMESPACE = "test"; + + @Test + void roundTripsExactAuthorizationAndCompleteRetainedTerminal() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var decodedRequest = + GameLogicIntakeRetainProtoCodec.fromRequest( + GameLogicIntakeRetainProtoCodec.toRequest(request)); + assertThat(decodedRequest).isEqualTo(request); + assertThat(decodedRequest.hashCode()).isEqualTo(request.hashCode()); + assertThat(decodedRequest.originalAuthorizationBytes()) + .containsExactly(authorization.canonicalBytes()); + + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var evidence = new GameLogicIntakeRetainEvidence(request, terminal); + var response = GameLogicIntakeRetainProtoCodec.toResponse(evidence); + var decoded = GameLogicIntakeRetainProtoCodec.fromResponse(request, response); + assertThat(response.getRequest()).isEqualTo(GameLogicIntakeRetainProtoCodec.toRequest(request)); + assertThat(decoded.terminal().canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES); + assertThat(GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES).isEqualTo(16 * 1024 * 1024); + assertThat(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES).isEqualTo(24 * 1024 * 1024); + } + + @Test + void rejectsUnknownFieldsChangedRequestEchoChangedBindingAndTerminalEvidence() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var terminal = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + var response = + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(request, terminal)); + + var requestWithUnknown = + GameLogicIntakeRetainProtoCodec.toRequest(request).toBuilder() + .setUnknownFields(unknownFields()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromRequest(requestWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + + var changedAuthorization = + new GameLogicIntakeAuthorizationBinding( + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.actorAccountId(), + authorization.source(), + authorization.sources()); + var changedRequest = + new GameLogicIntakeRetainEvidence.Request( + 1, NAMESPACE, request.correlationId(), changedAuthorization); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromResponse(changedRequest, response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new GameLogicIntakeRetainEvidence(request, terminalFor(changedAuthorization))) + .isInstanceOf(IllegalArgumentException.class); + + var badTerminalDigest = + response.toBuilder().setTerminalDigest("sha256:" + "0".repeat(64)).build(); + assertThatThrownBy( + () -> GameLogicIntakeRetainProtoCodec.fromResponse(request, badTerminalDigest)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedBytes = response.getOriginalTerminal().toByteArray(); + changedBytes[changedBytes.length - 1] ^= 1; + var changedTerminal = + response.toBuilder().setOriginalTerminal(ByteString.copyFrom(changedBytes)).build(); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromResponse(request, changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + + var responseWithUnknown = response.toBuilder().setUnknownFields(unknownFields()).build(); + assertThatThrownBy( + () -> GameLogicIntakeRetainProtoCodec.fromResponse(request, responseWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsTerminalForAnotherNamespaceEvenWhenAuthorizationBytesMatch() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create("other", authorization); + var terminalForWrongNamespace = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + + assertThatThrownBy(() -> new GameLogicIntakeRetainEvidence(request, terminalForWrongNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + } + + @Test + void rejectsOversizedAuthorizationAndTerminalAtTheirCanonicalLimits() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var oversizedAuthorization = + RetainGameplayRuleIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCorrelationId(UUID.randomUUID().toString()) + .setOriginalIntakeAuthorization( + ByteString.copyFrom( + new byte[GameLogicIntakeRetainEvidence.MAX_AUTHORIZATION_BYTES + 1])) + .setIntakeAuthorizationDigest(authorization.digest()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromRequest(oversizedAuthorization)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedTerminal = + RetainGameplayRuleIntakeResponse.newBuilder() + .setRequest(GameLogicIntakeRetainProtoCodec.toRequest(request)) + .setOriginalTerminal( + ByteString.copyFrom( + new byte[GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES + 1])) + .setTerminalDigest("sha256:" + "0".repeat(64)) + .build(); + assertThat(oversizedTerminal.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> GameLogicIntakeRetainProtoCodec.fromResponse(request, oversizedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsTerminalAboveDefaultGrpcMessageLimitWithinDeclaredWireLimit() { + var authorization = largeAuthorization(1800); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var response = + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(request, terminal)); + + assertThat(terminal.canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES); + assertThat( + GameLogicIntakeRetainProtoCodec.fromResponse(request, response) + .terminal() + .canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static GameLogicGameplayRuleIntakeTerminal terminalFor( + GameLogicIntakeAuthorizationBinding authorization) { + return GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selectedBinding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var selectedSource = source(selectedBinding); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selectedSource, + List.of(accountSource)); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + "0", + "revisionId", + binding.revisions().getFirst().revisionId().toString()))))); + } + + static GameLogicIntakeAuthorizationBinding largeAuthorization(int entryCount) { + UUID actor = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var requestId = UUID.randomUUID(); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(families); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java new file mode 100644 index 0000000000..5cce247e68 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -0,0 +1,755 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Actual loopback mTLS transport fixtures; these bytes do not establish creator provenance. */ +class GameLogicIntakeSourceReadTransportTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GrpcGameLogicIntakeSourceReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + private boolean stall; + private boolean substitute; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void close() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void roundTripsBothClosedProofsAndRejectsChangedEchoAndUnknownOrAbsentProof() { + for (var request : requests()) { + var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); + assertThat(GameLogicIntakeSourceReadProtoCodec.fromRequest(wire)).isEqualTo(request); + var response = GameLogicIntakeSourceReadProtoCodec.toResponse(request); + assertThat(GameLogicIntakeSourceReadProtoCodec.fromResponse(request, response).request()) + .isEqualTo(request); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setPermitted(false).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().clearAuthorizationProof().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setAuthorizationProofDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPurpose("PUBLICATION").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void pinsAccountServerAndAuthenticatedGdClientForBothMethods() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + for (var request : requests()) assertThat(client.read(request).request()).isEqualTo(request); + assertThat(calls).hasValue(2); + close(); + start(pki.wrongServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(requests().getFirst())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(2); + } + + @Test + void rejectsNamespaceAmbientSqlMissingTlsAndSubstitutedResponse() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeSourceReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeSourceReadClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var original = requests().getFirst(); + var otherNamespace = + new GameLogicIntakeSourceReadEvidence.Request( + 1, + "other", + UUID.randomUUID(), + "spiffe://firemud/ns/other/sa/game-logic-service", + original.purpose(), + requests().getLast().proof()); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(original)).isInstanceOf(IllegalStateException.class); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(false); + } + assertThat(calls).hasValue(0); + substitute = true; + assertThatThrownBy(() -> client.read(original)).isInstanceOf(IllegalStateException.class); + } + + @Test + void boundsUnavailableReadByDeadline() throws Exception { + stall = true; + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(requests().getFirst())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + + @Test + void rejectsOtherAuthenticatedClientWorkload() throws Exception { + start(pki.gameLogicServer()); + var wrongClient = + TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "wrong-source-client", + ACCOUNT_URI, + false); + client = newClient(wrongClient); + client.init(); + assertThatThrownBy(() -> client.read(requests().getFirst())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(0); + } + + @Test + void transportsResponsesOverFourMiBWithinBothExplicitWireBudgets() throws Exception { + // Deliberately synthetic owner evidence exercises envelope overhead, not creator authority. + var original = + ((GameplayRuleSourceReadEvidence.Finalized) requests().getLast().proof()).authorization(); + int padding = 4 * 1024 * 1024 - 16 - original.canonicalBytes().length + 1; + var large = + new GameLogicIntakeAuthorizationBinding( + original.operationId(), + original.fenceId(), + original.intakeRequestId(), + original.actorAccountId(), + original.source(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[padding]))); + assertThat(large.canonicalBytes().length).isEqualTo(4 * 1024 * 1024 - 16); + var permission = + GameLogicIntakeSourceReadEvidence.Request.create( + NAMESPACE, + "spiffe://firemud/ns/test/sa/game-logic-service", + GameLogicIntakeSourceReadScope.PURPOSE, + new GameplayRuleSourceReadEvidence.Finalized(large)); + assertThat(GameLogicIntakeSourceReadProtoCodec.toResponse(permission).getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES); + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThat(client.read(permission).request().proof().canonicalBytes()) + .containsExactly(large.canonicalBytes()); + close(); + + var sourceRequest = GameplayRuleSourceReadEvidence.Request.forFinalizedIntake(NAMESPACE, large); + var sourceEvidence = new GameplayRuleSourceReadEvidence(sourceRequest, large.source()); + assertThat(GameplayRuleSourceReadGrpcCodec.toResponse(sourceEvidence).getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES); + var gdServer = + TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "source-gd-server", + GD_URI, + true); + var glClient = + TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "source-gl-client", + "spiffe://firemud/ns/test/sa/game-logic-service", + false); + var sourceService = + new net.firedevops.firemud.gamedesign.v1.GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceImplBase() { + @Override + public void readSelectedGameplayRuleSource( + net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest wire, + StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse> + observer) { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/test/sa/game-logic-service"); + var request = GameplayRuleSourceReadGrpcCodec.fromRequest(wire); + observer.onNext( + GameplayRuleSourceReadGrpcCodec.toResponse( + new GameplayRuleSourceReadEvidence(request, large.source()))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(gdServer.privateKey(), gdServer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept(sourceService, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + try (var sourceClient = + new GameplayRuleSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, glClient), + new GrpcChannelFactory(), + NAMESPACE)) { + sourceClient.init(); + var result = sourceClient.read(sourceRequest); + assertThat(result.request().proof().canonicalBytes()).containsExactly(large.canonicalBytes()); + assertThat(result.source().canonicalBytes()).containsExactly(large.source().canonicalBytes()); + } + } + + @Test + void rejectsEnvelopesOverExplicitWireBudgetBeforeCanonicalDecode() { + var request = requests().getFirst(); + var oversizedAccount = + GameLogicIntakeSourceReadProtoCodec.toRequest(request).toBuilder() + .setPurpose("x".repeat(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES)) + .build(); + assertThatThrownBy(() -> GameLogicIntakeSourceReadProtoCodec.fromRequest(oversizedAccount)) + .isInstanceOf(IllegalArgumentException.class); + var sourceRequest = + GameplayRuleSourceReadEvidence.Request.forAccountSourceScope( + NAMESPACE, ((GameplayRuleSourceReadEvidence.Preliminary) request.proof()).scope()); + var oversizedGd = + GameplayRuleSourceReadGrpcCodec.toRequest(sourceRequest).toBuilder() + .setPurpose("x".repeat(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES)) + .build(); + assertThatThrownBy(() -> GameplayRuleSourceReadGrpcCodec.fromRequest(oversizedGd)) + .isInstanceOf(IllegalArgumentException.class); + } + + private void start(TestIdentity identity) throws Exception { + var service = + new AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceImplBase() { + @Override + public void readSourceScope( + GameLogicIntakeSourcePermissionRequest wire, + StreamObserver observer) { + respond(wire, observer, true); + } + + @Override + public void readFinalizedIntake( + GameLogicIntakeSourcePermissionRequest wire, + StreamObserver observer) { + respond(wire, observer, false); + } + + private void respond( + GameLogicIntakeSourcePermissionRequest wire, + StreamObserver observer, + boolean preliminary) { + if (!GD_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + calls.incrementAndGet(); + assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); + var request = GameLogicIntakeSourceReadProtoCodec.fromRequest(wire); + assertThat(request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary) + .isEqualTo(preliminary); + if (stall) return; + var response = GameLogicIntakeSourceReadProtoCodec.toResponse(request); + if (substitute) + response = + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build(); + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcGameLogicIntakeSourceReadClient newClient(TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GrpcGameLogicIntakeSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static List requests() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = selectedSource(binding); + var actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + binding, + ACCOUNT_URI, + GameLogicIntakeSourceReadScope.PURPOSE); + var auth = + new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return List.of( + GameLogicIntakeSourceReadEvidence.Request.create( + NAMESPACE, + ACCOUNT_URI, + scope.purpose(), + new GameplayRuleSourceReadEvidence.Preliminary(scope)), + GameLogicIntakeSourceReadEvidence.Request.create( + NAMESPACE, + "spiffe://firemud/ns/test/sa/game-logic-service", + scope.purpose(), + new GameplayRuleSourceReadEvidence.Finalized(auth))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + "0", + "revisionId", + binding.revisions().getFirst().revisionId().toString()))))); + } + + record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", GD_URI, false)); + } + + CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java new file mode 100644 index 0000000000..f1dc62a597 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -0,0 +1,624 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Structural and actual loopback-mTLS proof for the closed GL terminal read transport. */ +class GameLogicIntakeTerminalReadGrpcTest { + private static final String NAMESPACE = "test"; + private static final String GL_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final int LARGE_SOURCE_ENTRIES = 1800; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GameLogicIntakeTerminalReadClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void roundTripsRetainedAbortedAndExplicitAbsenceAndPreservesArrayValueSemantics() { + var small = evidence("test", 1, Outcome.RETAINED); + var retainedResponse = GameLogicIntakeTerminalReadGrpcCodec.toResponse(small); + var retained = + GameLogicIntakeTerminalReadGrpcCodec.fromResponse(small.request(), retainedResponse); + assertThat(retained.terminal().orElseThrow().canonicalBytes()) + .isEqualTo(small.terminal().orElseThrow().canonicalBytes()); + assertThat(retained.terminal().orElseThrow().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + + var aborted = evidence("test", 1, Outcome.ABORTED); + var abortedResponse = GameLogicIntakeTerminalReadGrpcCodec.toResponse(aborted); + assertThat( + GameLogicIntakeTerminalReadGrpcCodec.fromResponse(aborted.request(), abortedResponse) + .terminal() + .orElseThrow() + .outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + + var absent = new GameLogicIntakeTerminalReadEvidence(small.request(), Optional.empty()); + var absentResponse = GameLogicIntakeTerminalReadGrpcCodec.toResponse(absent); + assertThat(absentResponse.getAbsent()).isTrue(); + assertThat( + GameLogicIntakeTerminalReadGrpcCodec.fromResponse(small.request(), absentResponse) + .terminal()) + .isEmpty(); + + var requestWire = GameLogicIntakeTerminalReadGrpcCodec.toRequest(small.request()); + var decodedRequest = GameLogicIntakeTerminalReadGrpcCodec.fromRequest(requestWire); + assertThat(decodedRequest).isEqualTo(small.request()); + assertThat(decodedRequest.hashCode()).isEqualTo(small.request().hashCode()); + assertThat(decodedRequest.binding().canonicalBytes()) + .isEqualTo(small.request().binding().canonicalBytes()); + } + + @Test + void rejectsUnknownFieldsChangedOperationDigestAndTerminalPayload() { + var evidence = evidence("test", 1, Outcome.RETAINED); + var request = evidence.request(); + var response = GameLogicIntakeTerminalReadGrpcCodec.toResponse(evidence); + + var requestWithUnknown = + ReadGameplayRuleIntakeTerminalRequest.newBuilder() + .mergeFrom(GameLogicIntakeTerminalReadGrpcCodec.toRequest(request)) + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 100, + com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeTerminalReadGrpcCodec.fromRequest(requestWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + + var otherOperation = evidence("test", 1, Outcome.RETAINED).request().binding(); + var changedOperation = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setOriginalIntakeAuthorization( + ByteString.copyFrom(otherOperation.canonicalBytes())) + .setIntakeAuthorizationDigest(otherOperation.digest())) + .build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, changedOperation)) + .isInstanceOf(IllegalArgumentException.class); + + var changedDigest = response.toBuilder().setTerminalDigest("sha256:" + "0".repeat(64)).build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedPayload = response.getOriginalTerminal().toByteArray(); + changedPayload[changedPayload.length - 1] ^= 1; + var changedTerminal = + response.toBuilder().setOriginalTerminal(ByteString.copyFrom(changedPayload)).build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + + var responseWithUnknown = + response.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 100, + com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, responseWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void loopbackStrictMtlsTransportsLargeCanonicalTerminalAndPinsBothPeerIdentities() + throws Exception { + var large = evidence(NAMESPACE, LARGE_SOURCE_ENTRIES, Outcome.RETAINED); + byte[] terminalBytes = large.terminal().orElseThrow().canonicalBytes(); + assertThat(terminalBytes.length) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES); + assertThat(GameLogicIntakeTerminalReadGrpcCodec.toResponse(large).getSerializedSize()) + .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES); + + startServer(pki.gameLogicServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + var actual = client.read(large.request()); + assertThat(actual.terminal().orElseThrow().canonicalBytes()).isEqualTo(terminalBytes); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + + stopTransport(); + startServer(pki.wrongServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(large.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + private enum Outcome { + RETAINED, + ABORTED + } + + private void startServer(TestIdentity identity, GameLogicIntakeTerminalReadEvidence evidence) + throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceImplBase() { + @Override + public void readGameplayRuleIntakeTerminal( + ReadGameplayRuleIntakeTerminalRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = GameLogicIntakeTerminalReadGrpcCodec.fromRequest(wire); + var response = + GameLogicIntakeTerminalReadGrpcCodec.toResponse( + new GameLogicIntakeTerminalReadEvidence(request, evidence.terminal())); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameLogicIntakeTerminalReadClient newClient(Server target, TestIdentity local) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameLogicService("localhost:" + target.getPort()); + return new GameLogicIntakeTerminalReadClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ + private static GameLogicIntakeTerminalReadEvidence evidence( + String namespace, int entryCount, Outcome outcome) { + var tenant = UUID.randomUUID(); + var version = UUID.randomUUID(); + var requestId = UUID.randomUUID(); + var commitId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var definitionsByFamily = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + definitionsByFamily.put(family, new ArrayList<>()); + definitionsByFamily.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(definitionsByFamily); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountEvidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.fromString(accountEvidence.scopeId()), + source, + List.of(accountEvidence)); + var operation = new GameLogicGameplayRuleIntakeOperation(namespace, authorization); + var terminal = + outcome == Outcome.RETAINED + ? GameLogicGameplayRuleIntakeTerminal.retained( + operation, + source.canonicalBytes(), + manifest.canonicalJson().getBytes(StandardCharsets.UTF_8)) + : GameLogicGameplayRuleIntakeTerminal.aborted(operation); + return new GameLogicIntakeTerminalReadEvidence( + GameLogicIntakeTerminalReadEvidence.Request.create(namespace, authorization), + Optional.of(terminal)); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java new file mode 100644 index 0000000000..0c9b2f8a4d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java @@ -0,0 +1,354 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +class GameLogicPublicationSourceReadBindingTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID FENCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INTAKE_REQUEST = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID COMMIT = uuid("77777777-7777-4777-8777-777777777777"); + private static final String EXPECTED_PUBLICATION_PREIMAGE_HEX = + "32373a7075626c69636174696f6e446967657374526571756573742f7631383a74656e616e74496433363a" + + "31313131313131312d313131312d343131312d383131312d313131313131313131313131393a73636f7065" + + "4b696e6431323a46554c4c5f56455253494f4e393a76657273696f6e4964323a343131333a626173655665" + + "7273696f6e4964303a31383a736372697074506174636856657273696f6e303a31363a7075626c69736852" + + "657175657374496432313a7075626c69636174696f6e2d726571756573742d3132333a6465726976656457" + + "6f726b666c6f774964656e7469747938323a7075626c6973683a31313131313131312d313131312d343131" + + "312d383131312d3131313131313131313131313a7075626c6973682d726571756573743a7075626c696361" + + "74696f6e2d726571756573742d31"; + + @Test + void freezesExactThreeFramePreimageAndRoundTripsTheRetainedAuthorization() throws Exception { + var publicationRequest = publicationRequest(TENANT.toString(), "41"); + var authorization = authorization(OPERATION, FENCE, COMMIT, TENANT, 41); + var binding = new GameLogicPublicationSourceReadBinding(publicationRequest, authorization); + var fromAuthorizationBytes = + new GameLogicPublicationSourceReadBinding( + publicationRequest, authorization.canonicalBytes()); + byte[] publicationBytes = publicationRequest.canonicalPreimage(); + byte[] authorizationBytes = authorization.canonicalBytes(); + + assertThat(publicationBytes).hasSize(315); + assertThat(HexFormat.of().formatHex(publicationBytes)) + .isEqualTo(EXPECTED_PUBLICATION_PREIMAGE_HEX); + assertThat(authorization.digest()).isEqualTo(sha256(authorizationBytes)); + byte[] authorizationPrefix = + HexFormat.of() + .parseHex( + "0000002a6163636f756e742d67616d652d6c6f6769632d696e74616b652d617574686f72697a6174696f6e2f7631"); + byte[] authorizationSuffix = + HexFormat.of() + .parseHex( + "0000000750524553454e540000000131000000013100000006414253454e5400000003010203"); + assertThat(java.util.Arrays.copyOf(authorizationBytes, authorizationPrefix.length)) + .containsExactly(authorizationPrefix); + assertThat( + java.util.Arrays.copyOfRange( + authorizationBytes, + authorizationBytes.length - authorizationSuffix.length, + authorizationBytes.length)) + .containsExactly(authorizationSuffix); + + byte[] expectedPreimage = + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationBytes), + asciiFrame(authorizationBytes)); + assertThat(new String(expectedPreimage, 0, 40, StandardCharsets.US_ASCII)) + .isEqualTo("37:game-logic-publication-source-read/v1"); + assertThat(new String(expectedPreimage, 40, 4, StandardCharsets.US_ASCII)).isEqualTo("315:"); + int authorizationLengthOffset = 359; + assertThat( + new String( + expectedPreimage, + authorizationLengthOffset, + Integer.toString(authorizationBytes.length).length() + 1, + StandardCharsets.US_ASCII)) + .isEqualTo(authorizationBytes.length + ":"); + assertThat(binding.canonicalBytes()).containsExactly(expectedPreimage); + assertThat(binding.digest()).isEqualTo(sha256(expectedPreimage)); + assertThat(fromAuthorizationBytes.canonicalBytes()).containsExactly(expectedPreimage); + + var decoded = + GameLogicPublicationSourceReadBinding.fromStored(publicationRequest, expectedPreimage); + assertThat(decoded.publicationRequest()).isSameAs(publicationRequest); + assertThat(decoded.authorization().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(expectedPreimage); + assertThat(decoded.digest()).isEqualTo(binding.digest()); + byte[] returnedBytes = binding.canonicalBytes(); + returnedBytes[0] ^= 1; + assertThat(binding.canonicalBytes()).containsExactly(expectedPreimage); + } + + @Test + void rejectsMismatchedTenantVersionAndScriptPatchScope() { + var authorization = authorization(OPERATION, FENCE, COMMIT, TENANT, 41); + assertThatThrownBy( + () -> + new GameLogicPublicationSourceReadBinding( + publicationRequest("88888888-8888-4888-8888-888888888888", "41"), + authorization)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameLogicPublicationSourceReadBinding( + publicationRequest(TENANT.toString(), "42"), authorization)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.patch( + TENANT.toString(), "41", "patch-1", "pub-1"), + authorization)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bindsOperationFenceAndSelectedCommitBytesWithoutTreatingThemAsAuthority() { + var publicationRequest = publicationRequest(TENANT.toString(), "41"); + var original = + new GameLogicPublicationSourceReadBinding( + publicationRequest, authorization(OPERATION, FENCE, COMMIT, TENANT, 41)); + + var differentOperation = + new GameLogicPublicationSourceReadBinding( + publicationRequest, + authorization(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), FENCE, COMMIT, TENANT, 41)); + var differentFence = + new GameLogicPublicationSourceReadBinding( + publicationRequest, + authorization( + OPERATION, uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), COMMIT, TENANT, 41)); + var differentCommit = + new GameLogicPublicationSourceReadBinding( + publicationRequest, + authorization( + OPERATION, FENCE, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), TENANT, 41)); + + assertThat(differentOperation.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(differentOperation.digest()).isNotEqualTo(original.digest()); + assertThat(differentFence.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(differentFence.digest()).isNotEqualTo(original.digest()); + assertThat(differentCommit.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(differentCommit.digest()).isNotEqualTo(original.digest()); + } + + @Test + void rejectsMalformedNoncanonicalTruncatedTrailingAndOversizedFrames() { + var publicationRequest = publicationRequest(TENANT.toString(), "41"); + byte[] valid = + new GameLogicPublicationSourceReadBinding( + publicationRequest, authorization(OPERATION, FENCE, COMMIT, TENANT, 41)) + .canonicalBytes(); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(bytes("0"), valid))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(bytes("+"), valid))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, java.util.Arrays.copyOf(valid, valid.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationRequest.canonicalPreimage())))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(valid, asciiFrame(bytes("extra"))))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationRequest.canonicalPreimage()), + bytes("4194305:")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + new byte[GameLogicPublicationSourceReadBinding.MAX_TOTAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + + for (UUID identity : List.of(OPERATION, FENCE, COMMIT)) { + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + replaceFirst( + valid, + bytes(identity.toString()), + bytes("x" + identity.toString().substring(1))))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static PublicationDigestRequestBinding publicationRequest(String tenant, String version) { + return PublicationDigestRequestBinding.full(tenant, version, "publication-request-1"); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + UUID operation, UUID fence, UUID commit, UUID tenant, long versionRowId) { + DraftCommitBinding selected = selectedBinding(tenant, commit, versionRowId); + var source = selectedSource(selected); + var evidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + ACTOR.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + operation, fence, INTAKE_REQUEST, ACTOR, source, List.of(evidence)); + } + + private static DraftCommitBinding selectedBinding(UUID tenant, UUID commit, long versionRowId) { + var target = + new DraftCommitBinding.TargetProof( + tenant, VERSION, versionRowId, "private-tenant", 7, "private-tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + commit, + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + VERSION.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + "99999999-9999-4999-8999-999999999999", + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + "0", + "revisionId", + binding.revisions().getFirst().revisionId().toString()))))); + } + + private static byte[] asciiFrame(String value) { + return asciiFrame(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static byte[] asciiFrame(byte[] value) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value); + return output.toByteArray(); + } + + private static byte[] concat(byte[]... values) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (byte[] value : values) output.writeBytes(value); + return output.toByteArray(); + } + + private static byte[] replaceFirst(byte[] original, byte[] find, byte[] replacement) { + if (find.length != replacement.length) { + throw new IllegalArgumentException("Replacement must preserve byte length"); + } + byte[] result = original.clone(); + for (int start = 0; start <= result.length - find.length; start++) { + int index = 0; + while (index < find.length && result[start + index] == find[index]) index++; + if (index == find.length) { + System.arraycopy(replacement, 0, result, start, replacement.length); + return result; + } + } + throw new IllegalArgumentException("Expected fixture bytes were not found"); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String sha256(byte[] value) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java new file mode 100644 index 0000000000..a5f9cc5fcb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java @@ -0,0 +1,437 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class GameLogicPublicationSourceReadGrpcCodecTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID FENCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INTAKE_REQUEST = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID COMMIT = uuid("77777777-7777-4777-8777-777777777777"); + private static final String NAMESPACE = "test"; + + @Test + void roundTripsExactFullVersionRequestAndRetainedResponse() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + + GetDraftDesignDigestRequest request = + GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()); + assertThat(request.getTenantId()).isEqualTo(TENANT.toString()); + assertThat(request.getVersionId()).isEqualTo("41"); + assertThat(request.getBaseVersionId()).isEmpty(); + assertThat(request.getPublishRequestId()).isEqualTo("publication-request-1"); + assertThat(request.getDerivedWorkflowIdentity()) + .isEqualTo(fixture.binding().publicationRequest().derivedWorkflowIdentity()); + assertThat(request.getRequestDigest()) + .isEqualTo(fixture.binding().publicationRequest().requestDigest()); + assertThat(request.getSourceReadBinding().toByteArray()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(request.getSourceReadBindingDigest()).isEqualTo(fixture.binding().digest()); + assertThat(GameLogicPublicationSourceReadGrpcCodec.fromRequest(request).canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + var evidence = + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response, NAMESPACE); + assertThat(evidence.binding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(evidence.terminal().canonicalBytes()) + .containsExactly(fixture.terminal().canonicalBytes()); + assertThat(evidence.manifestDigest()).isEqualTo(response.getContentDigest()); + assertThat(evidence.abilitySchemaDigest()).isEqualTo(response.getAbilitySchemaDigest()); + assertThat(evidence.digestSchemaVersion()).isEqualTo(1); + assertThat(evidence.canonicalization()).isEqualTo("RFC8785"); + + assertThat( + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setError(ErrorDetail.getDefaultInstance()).build()) + .terminal() + .canonicalBytes()) + .containsExactly(fixture.terminal().canonicalBytes()); + } + + @Test + void rejectsChangedPublicationRequestIdentityScopeAndUnknownFields() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestRequest request = + GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setDerivedWorkflowIdentity("publish:wrong").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setRequestDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setScriptPatchVersion("patch-1").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) + .isInstanceOf(IllegalArgumentException.class); + byte[] substituted = request.getSourceReadBinding().toByteArray(); + substituted[0] ^= 1; + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder() + .setSourceReadBinding(ByteString.copyFrom(substituted)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + GetDraftDesignDigestRequest requestWithUnknown = + request.toBuilder().setUnknownFields(unknownField()).build(); + assertThatThrownBy( + () -> GameLogicPublicationSourceReadGrpcCodec.fromRequest(requestWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedResponseTenantVersionCommitAndBindingCorrelation() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + for (GetDraftDesignDigestResponse changed : + List.of( + response.toBuilder().setTenantId("88888888-8888-4888-8888-888888888888").build(), + response.toBuilder().setVersionId("42").build(), + response.toBuilder().setAppliedCommitId("88888888-8888-4888-8888-888888888888").build(), + response.toBuilder().setBaseVersionId("42").build(), + response.toBuilder().setScriptPatchVersion("patch-1").build(), + response.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) { + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + byte[] substitutedBinding = response.getSourceReadBinding().toByteArray(); + substitutedBinding[substitutedBinding.length - 1] ^= 1; + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setSourceReadBinding(ByteString.copyFrom(substitutedBinding)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setUnknownFields(unknownField()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedTerminalDigestOperationFenceCommitAndNamespace() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setRetainedIntakeTerminalDigest("sha256:changed").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response, "other")) + .isInstanceOf(IllegalArgumentException.class); + + List substitutedBindings = + List.of( + fixture( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), FENCE, COMMIT, TENANT, 41, NAMESPACE), + fixture( + OPERATION, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + COMMIT, + TENANT, + 41, + NAMESPACE), + fixture( + OPERATION, + FENCE, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + TENANT, + 41, + NAMESPACE)); + for (Fixture substituted : substitutedBindings) { + GetDraftDesignDigestResponse changed = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + substituted.binding(), substituted.terminal()); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + for (Fixture substitutedTerminal : substitutedBindings) { + GetDraftDesignDigestResponse changedTerminal = + response.toBuilder() + .setRetainedIntakeTerminal( + ByteString.copyFrom(substitutedTerminal.terminal().canonicalBytes())) + .setRetainedIntakeTerminalDigest(substitutedTerminal.terminal().digest()) + .build(); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + } + + Fixture wrongNamespace = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, "other"); + GetDraftDesignDigestResponse wrongNamespaceResponse = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + wrongNamespace.binding(), wrongNamespace.terminal()); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + wrongNamespace.binding(), wrongNamespaceResponse, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingAbortedMalformedOrOversizedTerminalAndNonemptyErrors() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response.toBuilder().clearRetainedIntakeTerminal().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setRetainedIntakeTerminal(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setRetainedIntakeTerminal( + ByteString.copyFrom( + new byte + [GameLogicPublicationSourceReadGrpcCodec.MAX_TERMINAL_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.toResponse( + fixture.binding(), + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation( + NAMESPACE, fixture.binding().authorization())))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedManifestAbilitySchemaVersionAndCanonicalization() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + for (GetDraftDesignDigestResponse changed : + List.of( + response.toBuilder().setContentDigest("sha256:changed").build(), + response.toBuilder().setAbilitySchemaDigest("sha256:changed").build(), + response.toBuilder().setDigestSchemaVersion(2).build(), + response.toBuilder().setCanonicalization("OTHER").build())) { + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void enforcesBindingByteLimitBeforeDecodingAndRejectsOversizedWireMessages() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestRequest oversizedBinding = + GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()).toBuilder() + .setSourceReadBinding( + ByteString.copyFrom( + new byte[GameLogicPublicationSourceReadGrpcCodec.MAX_BINDING_BYTES + 1])) + .build(); + assertThatThrownBy(() -> GameLogicPublicationSourceReadGrpcCodec.fromRequest(oversizedBinding)) + .isInstanceOf(IllegalArgumentException.class); + + GetDraftDesignDigestRequest oversizedWire = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId("x".repeat(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES)) + .build(); + assertThatThrownBy(() -> GameLogicPublicationSourceReadGrpcCodec.fromRequest(oversizedWire)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture( + UUID operationId, + UUID fenceId, + UUID commitId, + UUID tenantId, + long versionRowId, + String namespace) { + var publication = + PublicationDigestRequestBinding.full( + tenantId.toString(), Long.toString(versionRowId), "publication-request-1"); + var authorization = authorization(operationId, fenceId, commitId, tenantId, versionRowId); + var binding = new GameLogicPublicationSourceReadBinding(publication, authorization); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(namespace, authorization), + authorization.source().canonicalBytes(), + authorization + .source() + .manifest() + .canonicalJson() + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return new Fixture(binding, terminal); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + UUID operation, UUID fence, UUID commit, UUID tenant, long versionRowId) { + DraftCommitBinding selected = selectedBinding(tenant, commit, versionRowId); + var source = selectedSource(selected); + var evidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + ACTOR.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + operation, fence, INTAKE_REQUEST, ACTOR, source, List.of(evidence)); + } + + private static DraftCommitBinding selectedBinding(UUID tenant, UUID commit, long versionRowId) { + var target = + new DraftCommitBinding.TargetProof( + tenant, VERSION, versionRowId, "private-tenant", 7, "private-tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + commit, + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + VERSION.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + "99999999-9999-4999-8999-999999999999", + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + "0", + "revisionId", + binding.revisions().getFirst().revisionId().toString()))))); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java new file mode 100644 index 0000000000..979b73fabf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java @@ -0,0 +1,464 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import org.junit.jupiter.api.Test; + +class GameplayAbilitySchemaProjectionTest { + private static final String EMPTY_FAMILIES = + "\"ABILITIES\":[],\"ACTIONS\":[],\"ADMISSION_TAGS\":[],\"COMMANDS\":[],\"CONDITIONS\":[]," + + "\"CONTINUOUS_OVERLAYS\":[],\"DEFAULT_BINDINGS\":[],\"DISPOSITIONS\":[],\"EFFECTS\":[]," + + "\"FEEDBACK\":[],\"OBSERVATION_POLICIES\":[],\"RESOURCES\":[],\"SELECTION_POLICIES\":[]," + + "\"STATS\":[],\"TARGETING_POLICIES\":[]"; + private static final String EMPTY_VECTOR = + "{\"families\":{" + EMPTY_FAMILIES + "},\"schema\":\"gameplay-ability-schema/v1\"}"; + private static final String ROOT_VECTOR = + "{\"families\":{\"ABILITIES\":[{\"abilityId\":\"ability_a\",\"actionSequenceId\":\"action_a\",\"name\":\"A\"}]," + + "\"ACTIONS\":[{\"actionSequenceId\":\"action_a\",\"admissionTags\":[],\"cooldowns\":[],\"costs\":[]," + + "\"effects\":[],\"feedbackKeys\":[],\"name\":\"A\",\"targetSets\":[]}," + + "{\"actionSequenceId\":\"action_b\",\"admissionTags\":[],\"cooldowns\":[],\"costs\":[]," + + "\"effects\":[],\"feedbackKeys\":[],\"name\":\"B\",\"targetSets\":[]}]," + + EMPTY_FAMILIES.substring(EMPTY_FAMILIES.indexOf("\"ADMISSION_TAGS\"")) + + "},\"schema\":\"gameplay-ability-schema/v1\"}"; + + @Test + void frozenEmptyVectorIsDomainSeparatedAndDoesNotEstablishSourceAuthentication() { + var source = GameplayRuleManifest.explicitEmpty(); + assertThat(GameplayAbilitySchemaProjection.canonicalJson(source)).isEqualTo(EMPTY_VECTOR); + assertThat(GameplayAbilitySchemaProjection.digest(source)) + .isEqualTo("sha256:0207783645e944996b4f7589d2662d5b8309231769681e162ee05de51d34db2a"); + assertThat(GameplayAbilitySchemaProjection.digest(source)).isNotEqualTo(source.digest()); + // Content projection intentionally cannot manufacture a source operation or authenticated + // receipt. + assertThat(GameplayRuleManifest.tree(EMPTY_VECTOR).propertyNames()) + .containsExactly("families", "schema"); + assertThatThrownBy(() -> GameplayAbilitySchemaProjection.canonicalBytes(null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void frozenRootsVectorIncludesEveryActionEvenWithoutAnAbilityReference() { + var source = roots(); + assertThat(GameplayAbilitySchemaProjection.canonicalJson(source)).isEqualTo(ROOT_VECTOR); + assertThat(GameplayAbilitySchemaProjection.canonicalBytes(source)) + .isEqualTo(ROOT_VECTOR.getBytes(StandardCharsets.UTF_8)); + assertThat(GameplayAbilitySchemaProjection.digest(source)) + .isEqualTo("sha256:659a321a8fd1a02a4825a81568d67dee5039a1cb538756fb91c212aeaea1c536"); + } + + @Test + void allAbilityRootsAndOriginalFamilyOrderAffectTheProjection() { + var values = copy(roots()); + values + .get(Family.ABILITIES) + .add(new GameplayRuleManifest.Ability("ability_b", "B", "action_b")); + var both = new GameplayRuleManifest(values); + var reversed = copy(both); + java.util.Collections.reverse(reversed.get(Family.ABILITIES)); + assertThat(GameplayAbilitySchemaProjection.digest(both)) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(roots())); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(reversed))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(both)); + var actions = copy(both); + java.util.Collections.reverse(actions.get(Family.ACTIONS)); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(actions))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(both)); + } + + @Test + void followsTypedTransitivePredicateCostTargetEffectAndFeedbackEdgesIncludingCycles() { + var source = rich(); + var json = + GameplayRuleManifest.tree(GameplayAbilitySchemaProjection.canonicalJson(source)) + .path("families"); + for (Family family : + List.of( + Family.ABILITIES, + Family.ACTIONS, + Family.ADMISSION_TAGS, + Family.CONDITIONS, + Family.DISPOSITIONS, + Family.FEEDBACK, + Family.OBSERVATION_POLICIES, + Family.RESOURCES, + Family.SELECTION_POLICIES, + Family.STATS, + Family.TARGETING_POLICIES)) + assertThat(json.path(family.name()).size()).as(family.name()).isEqualTo(1); + assertThat(json.path("EFFECTS").size()).isEqualTo(2); + for (Family family : + List.of(Family.COMMANDS, Family.CONTINUOUS_OVERLAYS, Family.DEFAULT_BINDINGS)) + assertThat(json.path(family.name()).size()).as(family.name()).isZero(); + assertThat(json.path("EFFECTS").get(0).path("effectKey").textValue()).isEqualTo("drain"); + assertThat(json.path("EFFECTS").get(1).path("effectKey").textValue()).isEqualTo("mark_effect"); + assertThat(json.path("CONDITIONS").get(0).path("effectKeys").get(1).textValue()) + .isEqualTo("mark_effect"); + } + + @Test + void retainsCompleteTransitiveFieldsAndNestedArrayOrdering() { + var source = rich(); + var changed = copy(source); + var resource = (GameplayRuleManifest.Resource) changed.get(Family.RESOURCES).getFirst(); + changed + .get(Family.RESOURCES) + .set( + 0, + new GameplayRuleManifest.Resource( + resource.statKey(), + resource.defaultCurrent(), + resource.minimum(), + resource.defaultMaximum(), + resource.hardMaximum(), + resource.visibility(), + List.of("changed"))); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(changed))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(source)); + var reordered = copy(source); + var condition = (GameplayRuleManifest.Condition) reordered.get(Family.CONDITIONS).getFirst(); + reordered + .get(Family.CONDITIONS) + .set( + 0, + new GameplayRuleManifest.Condition( + condition.conditionKey(), + condition.reapplication(), + condition.durationPolicy(), + condition.durationTicks(), + condition.maximumStacks(), + condition.visibility(), + condition.tags(), + List.of("mark_effect", "drain"), + condition.removalPriority())); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(reordered))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(source)); + } + + @Test + void excludesUnreferencedCatalogAndCommandEditsButNotFromAggregate() { + var source = rich(); + var changed = copy(source); + changed + .get(Family.STATS) + .add( + new GameplayRuleManifest.Stat( + "unrelated", + GameplayRuleManifest.PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + null, + null, + GameplayRuleManifest.Visibility.PUBLIC, + List.of())); + var command = (GameplayRuleManifest.Command) changed.get(Family.COMMANDS).getFirst(); + changed + .get(Family.COMMANDS) + .set( + 0, + new GameplayRuleManifest.Command( + command.commandId(), + command.actionSequenceId(), + command.semanticOwner(), + command.executionDiscipline(), + command.stageRequirement(), + command.promptPolicy(), + command.actionCategory(), + command.historyRecordable(), + List.of("different_alias"), + command.actionTags(), + command.admissionTags())); + var other = new GameplayRuleManifest(changed); + assertThat(GameplayAbilitySchemaProjection.digest(other)) + .isEqualTo(GameplayAbilitySchemaProjection.digest(source)); + assertThat(other.digest()).isNotEqualTo(source.digest()); + } + + @Test + void rejectsIncompleteUnsupportedAndUnresolvedInputsEvenOutsideClosure() { + var missing = copy(roots()); + missing.remove(Family.DEFAULT_BINDINGS); + assertThatThrownBy( + () -> GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(missing))) + .isInstanceOf(IllegalArgumentException.class); + var unresolved = copy(roots()); + unresolved + .get(Family.COMMANDS) + .add( + new GameplayRuleManifest.Command( + "unrelated", + "missing", + "GAME_LOGIC", + GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY, + GameplayRuleManifest.Stage.GAMEPLAY, + GameplayRuleManifest.PromptPolicy.NEVER, + GameplayRuleManifest.ActionCategory.GAMEPLAY, + true, + List.of(), + List.of(), + List.of())); + assertThatThrownBy( + () -> GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(unresolved))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + roots() + .canonicalJson() + .replace("\"families\":", "\"unknown\":0,\"families\":"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + roots().canonicalJson().replace("gameplay-rule-manifest/v1", "unsupported/v1"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void numericEffectAndComparatorEdgesResolveTheirExactDeclaredFamily() { + var values = copy(rich()); + var original = (GameplayRuleManifest.Condition) values.get(Family.CONDITIONS).getFirst(); + values + .get(Family.CONDITIONS) + .set( + 0, + new GameplayRuleManifest.Condition( + original.conditionKey(), + original.reapplication(), + original.durationPolicy(), + original.durationTicks(), + original.maximumStacks(), + original.visibility(), + original.tags(), + List.of("drain", "mark_effect", "boost", "capacity"), + original.removalPriority())); + values + .get(Family.EFFECTS) + .add( + new GameplayRuleManifest.Effect( + "capacity", + GameplayRuleManifest.Lifecycle.CONTINUOUS, + GameplayRuleManifest.EffectOperation.ADD, + "mana", + GameplayRuleManifest.StatField.MAXIMUM, + BigDecimal.ONE, + null, + GameplayRuleManifest.CapacityChangePolicy.CLAMP_ONLY)); + var json = + GameplayRuleManifest.tree( + GameplayAbilitySchemaProjection.canonicalJson(new GameplayRuleManifest(values))) + .path("families"); + assertThat(json.path("EFFECTS").size()).isEqualTo(4); + assertThat(json.path("STATS").get(0).path("statKey").textValue()).isEqualTo("power"); + assertThat(json.path("RESOURCES").get(0).path("statKey").textValue()).isEqualTo("mana"); + values + .get(Family.SELECTION_POLICIES) + .set( + 0, + new GameplayRuleManifest.SelectionPolicy( + "select", + GameplayRuleManifest.Cardinality.EXACTLY_ONE, + null, + null, + GameplayRuleManifest.SelectionStrategy.RANKED, + null, + List.of( + new GameplayRuleManifest.RankComparator( + "power", + GameplayRuleManifest.StatField.VALUE, + GameplayRuleManifest.Direction.ASCENDING)))); + var statComparison = new GameplayRuleManifest(values); + assertThat( + GameplayRuleManifest.tree(GameplayAbilitySchemaProjection.canonicalJson(statComparison)) + .path("families") + .path("SELECTION_POLICIES") + .get(0) + .path("comparators") + .get(0) + .path("statKey") + .textValue()) + .isEqualTo("power"); + } + + private static GameplayRuleManifest roots() { + return manifest( + new GameplayRuleManifest.Ability("ability_a", "A", "action_a"), + action("action_a", "A"), + action("action_b", "B")); + } + + private static GameplayRuleManifest.Action action(String id, String name) { + return new GameplayRuleManifest.Action( + id, name, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + } + + private static GameplayRuleManifest rich() { + var target = + new GameplayRuleManifest.TargetSet("victim", "target", "select", false, "fb", null); + var truth = + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.TRUE, null, null, null, null, List.of()); + return manifest( + new GameplayRuleManifest.Ability("ability", "Ability", "act"), + new GameplayRuleManifest.Action( + "act", + "Action", + List.of("combat"), + List.of(target), + List.of( + new GameplayRuleManifest.Cost( + "mana", BigDecimal.ONE, GameplayRuleManifest.CommitPolicy.ON_EXECUTION)), + List.of( + new GameplayRuleManifest.Cooldown( + "cooldown", 3, GameplayRuleManifest.CommitPolicy.ON_EXECUTION)), + List.of(new GameplayRuleManifest.EffectBinding("mark_effect", "SOURCE")), + List.of("fb")), + new GameplayRuleManifest.Stat( + "power", + GameplayRuleManifest.PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + null, + null, + GameplayRuleManifest.Visibility.PUBLIC, + List.of()), + new GameplayRuleManifest.Resource( + "mana", + BigDecimal.ONE, + BigDecimal.ZERO, + BigDecimal.TEN, + BigDecimal.TEN, + GameplayRuleManifest.Visibility.PUBLIC, + List.of()), + new GameplayRuleManifest.Condition( + "mark", + GameplayRuleManifest.Reapplication.REPLACE, + GameplayRuleManifest.DurationPolicy.RESET, + 2L, + null, + GameplayRuleManifest.Visibility.PUBLIC, + List.of(), + List.of("drain", "mark_effect"), + 1), + new GameplayRuleManifest.Effect( + "drain", + GameplayRuleManifest.Lifecycle.INSTANT, + GameplayRuleManifest.EffectOperation.ADJUST_RESOURCE, + "mana", + null, + BigDecimal.ONE.negate(), + null, + null), + new GameplayRuleManifest.Effect( + "mark_effect", + GameplayRuleManifest.Lifecycle.INSTANT, + GameplayRuleManifest.EffectOperation.APPLY_CONDITION, + null, + null, + null, + "mark", + null), + new GameplayRuleManifest.Effect( + "boost", + GameplayRuleManifest.Lifecycle.CONTINUOUS, + GameplayRuleManifest.EffectOperation.ADD, + "power", + GameplayRuleManifest.StatField.VALUE, + BigDecimal.ONE, + null, + null), + new GameplayRuleManifest.AdmissionTag("combat"), + new GameplayRuleManifest.Disposition("hostile", List.of("combat"), "fb"), + new GameplayRuleManifest.ObservationPolicy( + "observe", + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.CONDITION_PRESENT, + GameplayRuleManifest.ActorRole.TARGET, + "mark", + null, + null, + List.of())), + new GameplayRuleManifest.TargetingPolicy( + "target", + GameplayRuleManifest.CandidateSelector.DIRECT_ACTOR, + "observe", + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.ALL, + null, + null, + null, + null, + List.of( + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.STAT_COMPARE, + GameplayRuleManifest.ActorRole.TARGET, + "power", + GameplayRuleManifest.Comparison.GE, + BigDecimal.ONE, + List.of()), + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.DISPOSITION_EQUALS, + GameplayRuleManifest.ActorRole.TARGET, + "hostile", + null, + null, + List.of()))), + "fb"), + new GameplayRuleManifest.SelectionPolicy( + "select", + GameplayRuleManifest.Cardinality.EXACTLY_ONE, + null, + null, + GameplayRuleManifest.SelectionStrategy.RANKED, + null, + List.of( + new GameplayRuleManifest.RankComparator( + "mana", + GameplayRuleManifest.StatField.MAXIMUM, + GameplayRuleManifest.Direction.DESCENDING))), + new GameplayRuleManifest.Feedback( + "fb", + "outcome", + GameplayRuleManifest.Audience.SOURCE_ACTOR, + "message", + "Safe feedback", + List.of(), + GameplayRuleManifest.Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT), + new GameplayRuleManifest.ContinuousOverlay( + "unrelated_overlay", truth, List.of("combat"), List.of("boost")), + new GameplayRuleManifest.DefaultBinding("unrelated_default", List.of(target)), + new GameplayRuleManifest.Command( + "unrelated_command", + "act", + "GAME_LOGIC", + GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY, + GameplayRuleManifest.Stage.GAMEPLAY, + GameplayRuleManifest.PromptPolicy.NEVER, + GameplayRuleManifest.ActionCategory.GAMEPLAY, + true, + List.of("alias"), + List.of(), + List.of("combat"))); + } + + private static GameplayRuleManifest manifest(Definition... definitions) { + Map> families = copy(GameplayRuleManifest.explicitEmpty()); + for (Definition definition : definitions) families.get(definition.family()).add(definition); + return new GameplayRuleManifest(families); + } + + private static Map> copy(GameplayRuleManifest source) { + Map> families = new EnumMap<>(Family.class); + source.families().forEach((family, values) -> families.put(family, new ArrayList<>(values))); + return families; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java new file mode 100644 index 0000000000..7b58481878 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -0,0 +1,450 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual loopback mTLS and 24 MiB wire proof using synthetic authoring evidence. */ +class GrpcGameLogicIntakeAuthorizationClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String CREDENTIAL = "unchanged.creator.credential"; + + @TempDir static Path tempDirectory; + private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private Server server; + private GrpcGameLogicIntakeAuthorizationClient client; + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicReference callerPeer = new AtomicReference<>(); + private final AtomicReference observedCredential = new AtomicReference<>(); + private final AtomicReference observedMethod = new AtomicReference<>(); + private volatile GameLogicIntakeAuthorizationResponse authorizeResponseOverride; + private volatile boolean stall; + + @BeforeAll + static void certificates() throws Exception { + pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + } + + @AfterEach + void closeTransport() throws Exception { + TransactionSynchronizationManager.clear(); + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var request = request(selected(1)); + var authorized = client.authorize(request, CREDENTIAL); + assertThat(authorized.outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); + assertThat(authorized.authorization().orElseThrow().intakeRequestId()) + .isEqualTo(request.intakeRequestId()); + var recovered = client.recover(request, CREDENTIAL); + assertThat(recovered.outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); + var aborted = client.abort(request, CREDENTIAL); + assertThat(aborted.outcome()).isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); + assertThat(calls).hasValue(3); + assertThat(callerPeer).hasValue(GD_URI); + assertThat(observedCredential).hasValue(CREDENTIAL); + assertThat(observedMethod.get()).contains("AbortIntake"); + } + + @Test + void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws Exception { + start(pki.wrongServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(0); + closeTransport(); + + start(pki.gameLogicServer()); + var wrongClient = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "wrong-game-design-client", + ACCOUNT_URI, + false); + client = newClient(wrongClient); + client.init(); + assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(0); + } + + @Test + void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var original = request(selected(1)); + var wrongNamespace = + new GameLogicIntakeAuthorizationEvidence.Request( + 1, "other", UUID.randomUUID(), UUID.randomUUID(), selected(1).canonicalBytes()); + assertThatThrownBy(() -> client.authorize(wrongNamespace, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(calls).hasValue(0); + closeTransport(); + + stall = true; + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + + @Test + void refusesPlaintextAndClasspathOrMissingTlsMaterial() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var classpathMaterial = new CommonGrpcClientProperties(); + classpathMaterial.setCertChain("classpath:account.crt"); + classpathMaterial.setPrivateKey("classpath:account.key"); + classpathMaterial.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, classpathMaterial, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit() + throws Exception { + var largeRequest = request(selected(4_500)); + var response = response(largeRequest, "AuthorizeIntake"); + assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); + authorizeResponseOverride = response; + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var actual = client.authorize(largeRequest, CREDENTIAL); + assertThat(actual.authorization().orElseThrow().canonicalBytes()) + .containsExactly( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(largeRequest, response) + .authorization() + .orElseThrow() + .canonicalBytes()); + } + + private void start(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) + throws Exception { + var service = + new AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceImplBase() { + @Override + public void authorizeIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + respond(request, observer, "AuthorizeIntake"); + } + + @Override + public void recoverIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + respond(request, observer, "RecoverIntake"); + } + + @Override + public void abortIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + respond(request, observer, "AbortIntake"); + } + + private void respond( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer, + String method) { + calls.incrementAndGet(); + observedMethod.set(method); + callerPeer.set(GrpcPeerIdentity.current().uri()); + observedCredential.set( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get().value()); + assertThat(Context.current().getDeadline()).isNotNull(); + if (stall) return; + var request = GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wire); + var override = "AuthorizeIntake".equals(method) ? authorizeResponseOverride : null; + if (override != null) { + assertThat(override.getRequest()).isEqualTo(wire); + observer.onNext(override); + } else { + observer.onNext(response(request, method)); + } + observer.onCompleted(); + } + }; + var credentialInterceptor = + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + Metadata headers, + io.grpc.ServerCallHandler next) { + if (!GD_URI.equals(GrpcPeerIdentity.current().uri())) { + call.close(Status.PERMISSION_DENIED, new Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + try { + var credential = + AccountGameLogicIntakeAuthorizationCredentials.readAuthenticated( + headers, call.getMethodDescriptor().getFullMethodName()); + return io.grpc.Contexts.interceptCall( + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, credential), + call, + headers, + next); + } catch (IllegalArgumentException malformed) { + call.close(Status.UNAUTHENTICATED, new Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, credentialInterceptor, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcGameLogicIntakeAuthorizationClient newClient( + GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static GameLogicIntakeAuthorizationEvidence.Request request(DraftCommitBinding selected) { + return GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selected); + } + + private static GameLogicIntakeAuthorizationResponse response( + GameLogicIntakeAuthorizationEvidence.Request request, String method) { + return GameLogicIntakeAuthorizationGrpcCodec.toResponse(result(request, method)); + } + + private static GameLogicIntakeAuthorizationEvidence.Result result( + GameLogicIntakeAuthorizationEvidence.Request request, String method) { + if ("AuthorizeIntake".equals(method)) + return GameLogicIntakeAuthorizationEvidence.Result.authorized( + request, authorization(request)); + var scope = scope(request); + return new GameLogicIntakeAuthorizationEvidence.Result( + request, + "AbortIntake".equals(method) + ? GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED + : GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED, + java.util.Optional.of(scope), + java.util.Optional.empty()); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeAuthorizationEvidence.Request request) { + UUID actor = UUID.randomUUID(); + var selected = request.selected(); + var source = selectedSource(selected); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static GameLogicIntakeSourceReadScope scope( + GameLogicIntakeAuthorizationEvidence.Request request) { + return new GameLogicIntakeSourceReadScope( + request.targetNamespace(), + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + UUID.randomUUID(), + request.selected(), + "spiffe://firemud/ns/" + request.targetNamespace() + "/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + } + + private static DraftCommitBinding selected(int revisionCount) { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var revisions = new ArrayList(revisionCount); + for (int index = 0; index < revisionCount; index++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding binding) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + var revision = binding.revisions().getLast(); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + revision.revisionOrder(), + "revisionId", + revision.revisionId().toString()))))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java new file mode 100644 index 0000000000..c2a6e431fb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS and message-size proof for the standalone GL intake retain client. */ +class GrpcGameLogicIntakeRetainClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GL_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + private static TestPki pki; + + private Server server; + private GrpcGameLogicIntakeRetainClient client; + private AtomicInteger calls; + private AtomicReference clientPeer; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void acceptsLargeTerminalFromExactGameLogicServerAndRejectsSubstitutedServer() throws Exception { + var authorization = GameLogicIntakeRetainProtoCodecTest.largeAuthorization(1800); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + byte[] expectedTerminal = terminal.canonicalBytes(); + assertThat(expectedTerminal.length).isGreaterThan(4 * 1024 * 1024); + + startServer(pki.gameLogicServer(), request, terminal); + client = newClient(server.getPort()); + client.init(); + var actual = client.retain(request); + assertThat(actual.terminal().canonicalBytes()).containsExactly(expectedTerminal); + assertThat(calls).hasValue(1); + assertThat(clientPeer).hasValue(GD_URI); + + stopTransport(); + startServer(pki.wrongServer(), request, terminal); + client = newClient(server.getPort()); + client.init(); + assertThatThrownBy(() -> client.retain(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + assertThat(clientPeer.get()).isNull(); + } + + private void startServer( + TestIdentity identity, + GameLogicIntakeRetainEvidence.Request expectedRequest, + GameLogicGameplayRuleIntakeTerminal terminal) + throws Exception { + calls = new AtomicInteger(); + clientPeer = new AtomicReference<>(); + var service = + new GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceImplBase() { + @Override + public void retainGameplayRuleIntake( + RetainGameplayRuleIntakeRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + clientPeer.set(peer == null ? null : peer.uri()); + var decoded = GameLogicIntakeRetainProtoCodec.fromRequest(wire); + assertThat(decoded).isEqualTo(expectedRequest); + observer.onNext( + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(decoded, terminal))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcGameLogicIntakeRetainClient newClient(int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameLogicService("localhost:" + port); + return new GrpcGameLogicIntakeRetainClient( + endpoints, + pki.clientProperties(tempDirectory, pki.gameDesignClient()), + new GrpcChannelFactory(), + NAMESPACE); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("intake-retain-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD intake-retain test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("intake-retain-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GD_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("intake-retain-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} From f46e421d452226cd6e79652373957b73927d62d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:38:52 +1300 Subject: [PATCH 02/22] Record qualified receiving proof for selected Game Logic intake --- .../implementation-tracking/player-access-and-session.md | 2 +- ...untGameLogicIntakeAuthorizationPostgresIntegrationTest.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f311733edd..c7e4b70b61 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The prepared Account source adds standalone Game Logic intake authorization, an immutable source-read reservation, exact finalized recovery, authorization reads, source reads and terminal settlement. It requires the same-namespace Game Design workload and current Account creator/environment evidence for fresh work. The actual selected Game Design source read precedes Account finalization; settlement independently reads the exact Game Logic terminal before Account SQL. Retained finalized recovery uses the original request and credential hash and never resumes a fresh source read. Common typed models, protobuf codecs and authenticated clients carry the complete immutable binding. The existing Account V95–V97 storage remains unchanged; these owners add no registration, route, enabling configuration or new SQL migration. -Local qualification passes the Account check/static/format and all five focused PostgreSQL cases on the canonical PostgreSQL 18 image: 1,414 Account units have no failures or errors and four known skips; native cases have no failures, errors or skips. The namespace proof uses actual Account reservation/finalization and retained original scope, refuses cross-namespace HELD, terminal dispatch, settlement and replay, and preserves six intake tables including row metadata. R3 Common proof executes 630 cases with one oversized large-wire fixture failure; the other 625 cases outside that five-case class remain passing at R3. After correcting the bounded fixture, R5 freshly passes all five mTLS client cases and full Common static/format checks in 43s, including an actual response above the default 4MiB limit and within the 24MiB transport bound. The final receiving parent and proof-status documentation remain to qualify. The native Account fixture controls the upstream ORIGINAL AUTHOR readback; it does not prove genuine authoring, the Game Logic retention pipeline or end-to-end settlement. The actual Game Logic intake owner and Game Design receipt pipeline are the next dependency, followed by selected launch-descriptor production. This prerequisite closes no genuine Gameplay handoff and does not resume Unit 1B/corpus. Canonical authority remains in [Account API contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); the receiving source consequence is recorded in [Gameplay Rules](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-intake-prerequisite). +Local qualification passes the Account check/static/format and all five focused PostgreSQL cases on the canonical PostgreSQL 18 image: 1,414 Account units have no failures or errors and four known skips; native cases have no failures, errors or skips. The namespace proof uses actual Account reservation/finalization and retained original scope, refuses cross-namespace HELD, terminal dispatch, settlement and replay, and preserves six intake tables including row metadata. R3 Common proof executes 630 cases with one oversized large-wire fixture failure; the other 625 cases outside that five-case class remain passing at R3. After correcting the bounded fixture, R5 freshly passes all five mTLS client cases and full Common static/format checks in 43s, including an actual response above the default 4MiB limit and within the 24MiB transport bound. R6 receives the published World preparation parent and passes the focused Account check/static/format, intake unit/native, Common compilation and documentation gate in 1m43s. All five native cases execute freshly without failures, errors or skips; unchanged broad units retain R3 attribution. Published CI and review remain separate. The native Account fixture controls the upstream ORIGINAL AUTHOR readback; it does not prove genuine authoring, the Game Logic retention pipeline or end-to-end settlement. The actual Game Logic intake owner and Game Design receipt pipeline are the next dependency, followed by selected launch-descriptor production. This prerequisite closes no genuine Gameplay handoff and does not resume Unit 1B/corpus. Canonical authority remains in [Account API contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); the receiving source consequence is recorded in [Gameplay Rules](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-intake-prerequisite). Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java index 3e5861746f..bf01191e01 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -55,7 +55,8 @@ class AccountGameLogicIntakeAuthorizationPostgresIntegrationTest { private static final Network NETWORK = Network.newNetwork(); @Container - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = From 029afc3a0c860fae5085364b07624cfb22d74970 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:58:07 +1300 Subject: [PATCH 03/22] Make Game Logic transport fixture flags visible across threads --- .../gamelogic/GameLogicIntakeSourceReadTransportTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index 5cce247e68..4dd282fe2c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -56,8 +56,8 @@ class GameLogicIntakeSourceReadTransportTest { private Server server; private GrpcGameLogicIntakeSourceReadClient client; private final AtomicInteger calls = new AtomicInteger(); - private boolean stall; - private boolean substitute; + private volatile boolean stall; + private volatile boolean substitute; @BeforeAll static void certificates() throws Exception { From 350bf9f065d9cb5c505ece1dd5e99376762e13c3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:26:37 +1300 Subject: [PATCH 04/22] Release Game Logic client monitors before watcher shutdown --- .../player-access-and-session.md | 6 + ...ameLogicIntakeAuthorizationReadClient.java | 8 +- .../GameLogicIntakeTerminalReadClient.java | 8 +- .../GameplayRuleSourceReadClient.java | 8 +- ...ntGameLogicIntakeSettlementReadClient.java | 8 +- ...rpcGameLogicIntakeAuthorizationClient.java | 8 +- .../GrpcGameLogicIntakeRetainClient.java | 8 +- .../GrpcGameLogicIntakeSourceReadClient.java | 8 +- .../GameLogicIntakeTerminalReadGrpcTest.java | 281 ++++++++++++++++++ 9 files changed, 322 insertions(+), 21 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 341407382b..b57a78bf7e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,6 +16,12 @@ Game Session now carries a default-off source path for current route and publish The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +### Game Logic intake client shutdown + +The seven explicit Game Logic source, authorization, terminal, retain and settlement clients now release their client monitor before the shared certificate watcher drains reload callbacks. Their local closed/initialized update remains synchronized. The seven lifecycle cases live in the existing [Game Logic intake terminal test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java), so this correction can remain with its intake owner without importing unrelated original-StartSession client fixtures. Request, peer, wire, owner and registration rules remain unchanged. + +The shared watcher matrix first reproduces all seven retained-monitor failures at test-only source `6bd5163d54c63ca9af6477af23fd1ce4eceb0f33`; nineteen earlier cases pass. Source `35261e8745d6805e0faaef088c41782708a07f33` passes 46 focused cases across six fresh XML reports and affected static analysis. After moving only those seven lifecycle cases into their existing Game Logic test owner, `49cd5fda35b4f83c922524fb9a05468e7ebc380e` passes all 27 selected cases across five fresh XML reports, with zero failures, errors or skips and affected static/formatting checks. Its seven production postimages are identical to `35261e8745`. The lifecycle cases exercise actual file-watch callbacks with mocked channels; the twenty other selected cases retain their controlled transport boundaries. These results establish no owner SQL, genuine issuer or source authority, deployed activation or Gameplay handoff completion. + ### Unregistered canonical runtime membership snapshot The local Account snapshot preparation uses [AccountCanonicalRuntimeMembershipSnapshotRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java) and [its transaction service](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java) to read existing canonical Account/tenant provenance, current owner generations and fence, roles, pair state and four exact source streams. It returns the existing shared content-validator carrier without writes. Tenant generations are equality-only; same-generation billing cutoff fields must equal the actual current tenant source/checkpoint, while different historical generations fail closed. The existing v1 tenant-event codec moved into Common with caller updates and a fixed full-payload/digest regression; the billing receipt remains provenance rather than entitlement authority. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java index dadb56b705..c6ec7ea3e5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java @@ -102,9 +102,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java index 900069c6f8..f5b4b72071 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java @@ -103,9 +103,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java index fbcc6e9844..75f541879d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java @@ -100,9 +100,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java index fc62e0ae82..2a6b1f4fbd 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java @@ -103,9 +103,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java index 70caa14ab4..9645b16ff6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java @@ -153,9 +153,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java index 6ec08f5c07..6f29847fb2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java @@ -100,9 +100,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java index 910b480dc7..1fe404d664 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java @@ -105,9 +105,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java index f1dc62a597..0ef151aa99 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -2,8 +2,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.Server; import io.grpc.ServerCall; @@ -18,6 +26,7 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -32,23 +41,35 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** Structural and actual loopback-mTLS proof for the closed GL terminal read transport. */ class GameLogicIntakeTerminalReadGrpcTest { @@ -58,6 +79,7 @@ class GameLogicIntakeTerminalReadGrpcTest { private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String STORE_PASSWORD = "test-only-store-password"; private static final int LARGE_SOURCE_ENTRIES = 1800; + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; @TempDir static Path tempDirectory; private static TestPki pki; @@ -84,6 +106,131 @@ void stopTransport() throws Exception { } } + /** Real file-watch contention with mocked channels, separate from the socket tests below. */ + @ParameterizedTest + @EnumSource(LifecycleClientKind.class) + @Timeout(30) + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void closeReleasesClientMonitorBeforeDrainingCertificateCallback( + LifecycleClientKind kind, @TempDir Path directory) throws Exception { + String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "true"); + CountDownLatch releaseClientMonitor = new CountDownLatch(1); + AtomicReference closeFailure = new AtomicReference<>(); + Thread monitorHolder = null; + Thread closeThread = null; + AbstractReloadingBlockingGrpcClient client = null; + TlsCertificateWatcher originalWatcher = null; + List channels = new CopyOnWriteArrayList<>(); + try { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameLogicService("game-logic.internal:6565"); + CommonGrpcClientProperties tls = lifecycleTls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + when(channelFactory.buildChannel( + any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenAnswer( + invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); + ClientHandle handle = kind.create(endpoints, tls, channelFactory); + client = handle.client(); + handle.initialize().run(); + AbstractReloadingBlockingGrpcClient clientUnderTest = client; + + originalWatcher = watcher(client); + Set activeCallbacks = activeCallbacks(originalWatcher); + TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); + TlsCertificateWatcher delegatedWatcher = originalWatcher; + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(clientUnderTest)) + .as("the client monitor must be released before watcher shutdown") + .isFalse(); + delegatedWatcher.close(); + return null; + }) + .when(closeBoundary) + .close(); + setWatcher(clientUnderTest, closeBoundary); + CountDownLatch clientMonitorHeld = new CountDownLatch(1); + monitorHolder = + new Thread( + () -> { + synchronized (clientUnderTest) { + clientMonitorHeld.countDown(); + awaitLatch(releaseClientMonitor); + } + }, + "game-logic-intake-client-monitor-holder"); + monitorHolder.start(); + assertThat(clientMonitorHeld.await(5, TimeUnit.SECONDS)).isTrue(); + + CountDownLatch closeStarted = new CountDownLatch(1); + Thread closeWorker = + new Thread( + () -> { + closeStarted.countDown(); + try { + clientUnderTest.close(); + } catch (Throwable failure) { + closeFailure.set(failure); + } + }, + "game-logic-intake-client-close"); + closeThread = closeWorker; + closeWorker.start(); + assertThat(closeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); + + Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); + Thread callback = awaitBlockedReloadCallback(activeCallbacks); + assertThat(callback).isNotNull(); + + releaseClientMonitor.countDown(); + closeWorker.join(TimeUnit.SECONDS.toMillis(4)); + assertThat(closeWorker.isAlive()) + .as("close must not hold the client monitor while the watcher drains its callback") + .isFalse(); + assertThat(closeFailure.get()).isNull(); + + clientUnderTest.close(); + assertThatThrownBy(() -> handle.initialize().run()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + assertThat(channels).isNotEmpty(); + for (ManagedChannel channel : channels) { + verify(channel, times(1)).shutdown(); + } + } finally { + releaseClientMonitor.countDown(); + if (monitorHolder != null) { + monitorHolder.join(TimeUnit.SECONDS.toMillis(5)); + } + if (closeThread != null) { + closeThread.join(TimeUnit.SECONDS.toMillis(7)); + } + try { + if (originalWatcher != null) { + originalWatcher.close(); + } + } finally { + try { + if (client != null) { + if (originalWatcher != null) { + setWatcher(client, originalWatcher); + } + client.close(); + } + } finally { + restoreReloadPolicy(previousReloadPolicy); + } + } + } + } + @Test void roundTripsRetainedAbortedAndExplicitAbsenceAndPreservesArrayValueSemantics() { var small = evidence("test", 1, Outcome.RETAINED); @@ -621,4 +768,138 @@ private static Path writePem(Path path, String label, byte[] bytes) throws IOExc StandardCharsets.US_ASCII); } } + + @FunctionalInterface + private interface Initialize { + void run() throws Exception; + } + + private record ClientHandle( + AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} + + private enum LifecycleClientKind { + GAME_LOGIC_AUTHORIZATION_READ, + GAME_LOGIC_TERMINAL_READ, + GAMEPLAY_RULE_SOURCE_READ, + ACCOUNT_GAME_LOGIC_SETTLEMENT_READ, + GAME_LOGIC_INTAKE_AUTHORIZATION, + GAME_LOGIC_INTAKE_RETAIN, + GAME_LOGIC_INTAKE_SOURCE_READ; + + ClientHandle create( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory) { + return switch (this) { + case GAME_LOGIC_AUTHORIZATION_READ -> { + var client = new GameLogicIntakeAuthorizationReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_LOGIC_TERMINAL_READ -> { + var client = new GameLogicIntakeTerminalReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAMEPLAY_RULE_SOURCE_READ -> { + var client = new GameplayRuleSourceReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_GAME_LOGIC_SETTLEMENT_READ -> { + var client = + new GrpcAccountGameLogicIntakeSettlementReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_LOGIC_INTAKE_AUTHORIZATION -> { + var client = new GrpcGameLogicIntakeAuthorizationClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_LOGIC_INTAKE_RETAIN -> { + var client = new GrpcGameLogicIntakeRetainClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_LOGIC_INTAKE_SOURCE_READ -> { + var client = new GrpcGameLogicIntakeSourceReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + }; + } + } + + private static Thread awaitBlockedReloadCallback(Set activeCallbacks) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + for (Thread callback : activeCallbacks) { + if (callback.getState() == Thread.State.BLOCKED + && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { + return callback; + } + } + Thread.sleep(10); + } + return null; + } + + private static boolean hasFrame(Thread thread, String className, String methodName) { + for (StackTraceElement frame : thread.getStackTrace()) { + if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + + private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!condition.getAsBoolean() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertThat(condition.getAsBoolean()).isTrue(); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + + private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + return (TlsCertificateWatcher) field.get(client); + } + + private static void setWatcher( + AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + field.set(client, watcher); + } + + @SuppressWarnings("unchecked") + private static Set activeCallbacks(TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); + field.setAccessible(true); + return (Set) field.get(watcher); + } + + private static void restoreReloadPolicy(String previousPolicy) { + if (previousPolicy == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previousPolicy); + } + } + + private static CommonGrpcClientProperties lifecycleTls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } } From 9abb35de2c9d8441ab1c3bcea129ad9fceee2b4a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:48:18 +1300 Subject: [PATCH 05/22] Record targeted Controller status deadline friction --- design/project-management/ai-observations.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0c12deb423..0dad25ee12 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -139,3 +139,7 @@ Entry format: - 2026-10-17 — Distinguish queued source CI from early metadata runs. - Observation: The Gameplay observer initially reported that six newly published heads had no source validation because only their early metadata jobs were inspectable. Their original source workflows subsequently completed change detection and started the build/test matrices. No missing-source CI defect or cancellation was established; the premature report sent unnecessary investigation to Overseer. - Expected pattern: Retain each original run and classify source selection as pending or unknown while discovery or queue admission is incomplete. A completed metadata gate establishes neither source success nor source absence. The report and observer guidance were corrected with the exact source run identities. + +- 2026-10-17 — Targeted Controller status can exhaust its deadline on older queue history. + - Observation: `firemud-controller --worker-identity Gameplay reviews status --pr 3224 --json` failed at its 120-second deadline during `target_history_pr_2846_cli`, after eighty prior phases consumed 119.6 seconds. It returned no JSON, delaying current front readiness readback even though publication and direct head/base verification succeeded. + - Expected pattern: Keep current-target status bounded while retaining historical review evidence. Overseer received the exact diagnostic; no state deletion, quota reset or installed-runtime bypass was used. The subsequent exact-checkpoint ancestry reconciliations succeeded; the failed status invocation itself remains unavailable evidence. From 7c224c09b17cab422b487a188d77dc27191fa1b5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:49:48 +1300 Subject: [PATCH 06/22] Record nonblocking predecessor Hosted recapture warning --- design/project-management/ai-observations.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0dad25ee12..a7173e4e25 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -143,3 +143,7 @@ Entry format: - 2026-10-17 — Targeted Controller status can exhaust its deadline on older queue history. - Observation: `firemud-controller --worker-identity Gameplay reviews status --pr 3224 --json` failed at its 120-second deadline during `target_history_pr_2846_cli`, after eighty prior phases consumed 119.6 seconds. It returned no JSON, delaying current front readiness readback even though publication and direct head/base verification succeeded. - Expected pattern: Keep current-target status bounded while retaining historical review evidence. Overseer received the exact diagnostic; no state deletion, quota reset or installed-runtime bypass was used. The subsequent exact-checkpoint ancestry reconciliations succeeded; the failed status invocation itself remains unavailable evidence. + +- 2026-10-17 — Repeated Hosted capture can reject a previously finalized provider comment. + - Observation: Admission of #3231’s second Hosted review reported a nonblocking `predecessor_terminal_capture` warning for its already-finalized first review: `Hosted finding comment contains unmarked content after its final cr-comment:v1 marker`. The original seven findings, accepted-fix records and checkpoint 6214527024 had already been recorded; the next request posted successfully as trigger 6214841384. The exact trailing-content cause remains unverified. + - Expected pattern: Preserve completed review evidence and surface the exact capture incompatibility without silently replacing counts or requiring a quota reset. Overseer received the retained diagnostic; Gameplay made no database or installed-runtime bypass. From 3adc9d97571f54e7f14c1ce0583fb191f9c1725f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:44:51 +1300 Subject: [PATCH 07/22] fix: preserve intake transport failure and message bounds --- .../account-service/api-contracts.md | 2 +- ...tGameLogicIntakeSettlementGrpcService.java | 16 +- ...eLogicIntakeSettlementGrpcServiceTest.java | 10 +- ...ameLogicIntakeAuthorizationReadClient.java | 1 + ...rpcGameLogicIntakeAuthorizationClient.java | 5 +- ...IntakeAuthorizationReadClientMtlsTest.java | 284 ++++++++++++++++++ ...ogicIntakeAuthorizationClientMtlsTest.java | 31 ++ 7 files changed, 343 insertions(+), 6 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2f2e17b8d8..a31eb60b3f 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. +The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling a standalone HELD-read server, its receiving limit must allow the existing `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES` request bound; this is a required receiver configuration, not a claim about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java index d1d8f738d2..60d644e833 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java @@ -60,9 +60,21 @@ public void settleGameLogicIntake( deny(observer, Status.PERMISSION_DENIED); return; } + final AccountGameLogicIntakeSettlement receipt; + try { + receipt = owner.settle(request.binding()); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (IllegalArgumentException changedPrecondition) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } final SettleGameLogicIntakeResponse response; try { - var receipt = owner.settle(request.binding()); response = AccountGameLogicIntakeSettlementProtoCodec.toResponse( new AccountGameLogicIntakeSettlementReadEvidence( @@ -70,7 +82,7 @@ public void settleGameLogicIntake( } catch (StatusRuntimeException failure) { deny(observer, Status.fromCode(failure.getStatus().getCode())); return; - } catch (RuntimeException unavailable) { + } catch (RuntimeException malformedReceipt) { deny(observer, Status.UNAVAILABLE); return; } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java index a2ecb6a2b0..fc71c91c70 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -114,7 +114,7 @@ void returnsExactRetainedAndAbortedReceiptForNewCorrelationRetryWithoutChangingB } @Test - void substitutedOwnerReceiptAndOwnerFailureDenyWithoutLeakingDiagnostics() { + void substitutedReceiptAndOwnerFailuresDenyWithoutLeakingDiagnostics() { var evidence = evidence("test", 1, Outcome.RETAINED); var request = AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()); when(owner.settle(any())) @@ -122,6 +122,14 @@ void substitutedOwnerReceiptAndOwnerFailureDenyWithoutLeakingDiagnostics() { new AccountGameLogicIntakeSettlement( evidence("test", 1, Outcome.RETAINED).receipt().terminal())); assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.UNAVAILABLE); + when(owner.settle(any())).thenThrow(new IllegalArgumentException("private-stale-precondition")); + var stalePrecondition = authorized(() -> invoke(request)); + assertThat(stalePrecondition.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(stalePrecondition.error().toString()).doesNotContain("private-stale-precondition"); + when(owner.settle(any())).thenThrow(new IllegalStateException("private-storage-failure")); + var storageFailure = authorized(() -> invoke(request)); + assertThat(storageFailure.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(storageFailure.error().toString()).doesNotContain("private-storage-failure"); when(owner.settle(any())) .thenThrow( Status.FAILED_PRECONDITION diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java index c6ec7ea3e5..19168fa1b3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java @@ -96,6 +96,7 @@ protected String defaultTarget() { buildStub(ManagedChannel channel) { String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; return AccountGameLogicIntakeAuthorizationReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java index 9645b16ff6..ee3e455191 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java @@ -87,6 +87,8 @@ private GameLogicIntakeAuthorizationEvidence.Result invoke( var current = stub(); if (closed || !initialized || current == null) throw new IllegalStateException("Account intake authorization client unavailable"); + var credentials = credentials(originalCreatorCredential, operation); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); try { var secured = current @@ -94,9 +96,8 @@ private GameLogicIntakeAuthorizationEvidence.Result invoke( new CompositeCallCredentials( new GrpcServerPeerIdentityCallCredentials( "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"), - credentials(originalCreatorCredential, operation))) + credentials)) .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); - var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); var response = switch (operation) { case AUTHORIZE -> secured.authorizeIntake(wireRequest); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java new file mode 100644 index 0000000000..3063692f93 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Actual loopback mTLS proof for the unregistered Account HELD authorization read. */ +class GameLogicIntakeAuthorizationReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_LOGIC_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final int MAX_BINDING_BYTES = 4 * 1024 * 1024; + + @TempDir static Path tempDirectory; + private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private Server server; + private GameLogicIntakeAuthorizationReadClient client; + private GameLogicIntakeAuthorizationReadEvidence.Request expectedRequest; + private final AtomicInteger calls = new AtomicInteger(); + + @BeforeAll + static void certificates() throws Exception { + pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + } + + @AfterEach + void closeTransport() throws Exception { + close(); + } + + @Test + void readsLargeExactHeldBindingOverPinnedLoopbackMtls() throws Exception { + var base = authorizationBinding(); + int padding = MAX_BINDING_BYTES - base.canonicalBytes().length; + var large = + new GameLogicIntakeAuthorizationBinding( + base.operationId(), + base.fenceId(), + base.intakeRequestId(), + base.actorAccountId(), + base.source(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + base.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[padding]))); + assertThat(large.canonicalBytes()).hasSize(MAX_BINDING_BYTES - 1); + expectedRequest = GameLogicIntakeAuthorizationReadEvidence.Request.create(NAMESPACE, large); + var wireRequest = GameLogicIntakeAuthorizationReadGrpcCodec.toRequest(expectedRequest); + var wireResponse = GameLogicIntakeAuthorizationReadGrpcCodec.toHeldResponse(expectedRequest); + assertThat(wireRequest.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(wireResponse.getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); + + start(pki.gameLogicServer()); + client = newClient(gameLogicClient()); + client.init(); + var actual = client.read(expectedRequest); + assertThat(actual.request()).isEqualTo(expectedRequest); + assertThat(actual.request().binding().canonicalBytes()).containsExactly(large.canonicalBytes()); + assertThat(calls).hasValue(1); + } + + @Test + void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { + start(pki.wrongServer()); + client = newClient(gameLogicClient()); + client.init(); + var request = + GameLogicIntakeAuthorizationReadEvidence.Request.create( + NAMESPACE, authorizationBinding()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(0); + close(); + + start(pki.gameLogicServer()); + client = newClient(otherCaller()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(0); + } + + private void start(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) + throws Exception { + var service = + new AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceImplBase() { + @Override + public void readHeldGameLogicIntakeAuthorization( + ReadHeldGameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + if (!GAME_LOGIC_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + calls.incrementAndGet(); + var decoded = GameLogicIntakeAuthorizationReadGrpcCodec.fromRequest(wire); + assertThat(decoded).isEqualTo(expectedRequest); + observer.onNext(GameLogicIntakeAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameLogicIntakeAuthorizationReadClient newClient( + GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GameLogicIntakeAuthorizationReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private GameLogicIntakeSourceReadTransportTest.TestIdentity gameLogicClient() throws Exception { + return GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "game-logic-client", + GAME_LOGIC_URI, + false); + } + + private GameLogicIntakeSourceReadTransportTest.TestIdentity otherCaller() throws Exception { + return GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "other-client", + "spiffe://firemud/ns/test/sa/game-design-service", + false); + } + + private static GameLogicIntakeAuthorizationBinding authorizationBinding() { + UUID tenant = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + var revision = binding.revisions().getFirst(); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + revision.revisionOrder(), + "revisionId", + revision.revisionId().toString()))))); + UUID actor = UUID.randomUUID(); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private void close() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 7b58481878..0552abf53f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; import io.grpc.Context; import io.grpc.Metadata; import io.grpc.Server; @@ -212,6 +213,36 @@ void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit .canonicalBytes()); } + @Test + void rejectsMalformedCreatorCredentialsBeforeRpcAndSanitizesMalformedEvidence() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var request = request(selected(1)); + for (String malformed : List.of(" ", "x".repeat(16385))) { + assertThatThrownBy(() -> client.authorize(request, malformed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid Game Logic intake credential metadata"); + } + assertThat(calls).hasValue(0); + + String sensitive = "sensitive-malformed-account-evidence"; + authorizeResponseOverride = + response(request, "AuthorizeIntake") + .toBuilder() + .setFinalizedIntakeAuthorization(ByteString.copyFromUtf8(sensitive)) + .build(); + assertThatThrownBy(() -> client.authorize(request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account returned invalid Game Logic intake authorization evidence") + .satisfies( + failure -> { + assertThat(failure.getCause()).isNull(); + assertThat(failure.getMessage()).doesNotContain(sensitive); + }); + assertThat(calls).hasValue(1); + } + private void start(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { var service = From ea81bbfaa486f4778a1636f9a33150bda356f68f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:50:26 +1300 Subject: [PATCH 08/22] test: correct intake transport fixture reuse and throwing stubs --- ...ntGameLogicIntakeSettlementGrpcServiceTest.java | 14 +++++++++----- ...LogicIntakeAuthorizationReadClientMtlsTest.java | 14 ++++++++++---- ...GameLogicIntakeAuthorizationClientMtlsTest.java | 3 +-- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java index fc71c91c70..c1c51a64bd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -122,19 +123,22 @@ void substitutedReceiptAndOwnerFailuresDenyWithoutLeakingDiagnostics() { new AccountGameLogicIntakeSettlement( evidence("test", 1, Outcome.RETAINED).receipt().terminal())); assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.UNAVAILABLE); - when(owner.settle(any())).thenThrow(new IllegalArgumentException("private-stale-precondition")); + doThrow(new IllegalArgumentException("private-stale-precondition")) + .when(owner) + .settle(any()); var stalePrecondition = authorized(() -> invoke(request)); assertThat(stalePrecondition.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); assertThat(stalePrecondition.error().toString()).doesNotContain("private-stale-precondition"); - when(owner.settle(any())).thenThrow(new IllegalStateException("private-storage-failure")); + doThrow(new IllegalStateException("private-storage-failure")).when(owner).settle(any()); var storageFailure = authorized(() -> invoke(request)); assertThat(storageFailure.code()).isEqualTo(Status.Code.UNAVAILABLE); assertThat(storageFailure.error().toString()).doesNotContain("private-storage-failure"); - when(owner.settle(any())) - .thenThrow( + doThrow( Status.FAILED_PRECONDITION .withDescription("private-owner-evidence") - .asRuntimeException()); + .asRuntimeException()) + .when(owner) + .settle(any()); var failed = authorized(() -> invoke(request)); assertThat(failed.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); assertThat(failed.error().toString()).doesNotContain("private-owner-evidence"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java index 3063692f93..9df7ff93c7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -43,6 +43,7 @@ class GameLogicIntakeAuthorizationReadClientMtlsTest { @TempDir static Path tempDirectory; private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity gameLogicClientIdentity; private Server server; private GameLogicIntakeAuthorizationReadClient client; private GameLogicIntakeAuthorizationReadEvidence.Request expectedRequest; @@ -51,6 +52,7 @@ class GameLogicIntakeAuthorizationReadClientMtlsTest { @BeforeAll static void certificates() throws Exception { pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + gameLogicClientIdentity = issueIdentity("game-logic-client", GAME_LOGIC_URI); } @AfterEach @@ -102,8 +104,7 @@ void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { client = newClient(gameLogicClient()); client.init(); var request = - GameLogicIntakeAuthorizationReadEvidence.Request.create( - NAMESPACE, authorizationBinding()); + GameLogicIntakeAuthorizationReadEvidence.Request.create(NAMESPACE, authorizationBinding()); assertThatThrownBy(() -> client.read(request)).isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(0); close(); @@ -166,12 +167,17 @@ private GameLogicIntakeAuthorizationReadClient newClient( } private GameLogicIntakeSourceReadTransportTest.TestIdentity gameLogicClient() throws Exception { + return gameLogicClientIdentity; + } + + private static GameLogicIntakeSourceReadTransportTest.TestIdentity issueIdentity( + String alias, String workloadUri) throws Exception { return GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( tempDirectory, tempDirectory.resolve("terminal-test-ca.p12"), tempDirectory.resolve("terminal-test-ca.crt"), - "game-logic-client", - GAME_LOGIC_URI, + alias, + workloadUri, false); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 0552abf53f..6c6a2e02ff 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -228,8 +228,7 @@ void rejectsMalformedCreatorCredentialsBeforeRpcAndSanitizesMalformedEvidence() String sensitive = "sensitive-malformed-account-evidence"; authorizeResponseOverride = - response(request, "AuthorizeIntake") - .toBuilder() + response(request, "AuthorizeIntake").toBuilder() .setFinalizedIntakeAuthorization(ByteString.copyFromUtf8(sensitive)) .build(); assertThatThrownBy(() -> client.authorize(request, CREDENTIAL)) From b11f525ffba148b354a7f37b5bcda4c5a157f7e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:53:02 +1300 Subject: [PATCH 09/22] style: apply canonical intake transport test formatting --- .../AccountGameLogicIntakeSettlementGrpcServiceTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java index c1c51a64bd..cf6c5547ad 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -123,9 +123,7 @@ void substitutedReceiptAndOwnerFailuresDenyWithoutLeakingDiagnostics() { new AccountGameLogicIntakeSettlement( evidence("test", 1, Outcome.RETAINED).receipt().terminal())); assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.UNAVAILABLE); - doThrow(new IllegalArgumentException("private-stale-precondition")) - .when(owner) - .settle(any()); + doThrow(new IllegalArgumentException("private-stale-precondition")).when(owner).settle(any()); var stalePrecondition = authorized(() -> invoke(request)); assertThat(stalePrecondition.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); assertThat(stalePrecondition.error().toString()).doesNotContain("private-stale-precondition"); From bad24afd3f0805f15342da081dceb4b28c87e66f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:21:44 +1300 Subject: [PATCH 10/22] fix: clear exempt RPC thread context across lifecycle callbacks --- .../common/security/AuthTokenInterceptor.java | 52 +++- .../security/AuthTokenInterceptorTest.java | 279 ++++++++++++++++++ 2 files changed, 330 insertions(+), 1 deletion(-) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java index a9992ad1e4..7b060396cb 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java @@ -33,8 +33,19 @@ public AuthTokenInterceptor(JwtUtil jwtUtil, Set unauthenticatedMethods) public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { if (unauthenticatedMethods.contains(call.getMethodDescriptor().getFullMethodName())) { + ServerCall clearingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void close(Status status, Metadata trailers) { + runWithClearedSessionContext(() -> super.close(status, trailers)); + } + }; SessionContext.clear(); - return next.startCall(call, headers); + try { + return withClearedSessionContextCallbacks(next.startCall(clearingCall, headers)); + } finally { + SessionContext.clear(); + } } String authHeader = headers.get(AUTH_HEADER); if (authHeader == null || !authHeader.startsWith("Bearer ")) { @@ -83,4 +94,43 @@ public void onCancel() { return new ServerCall.Listener<>() {}; } } + + private static ServerCall.Listener withClearedSessionContextCallbacks( + ServerCall.Listener listener) { + return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + runWithClearedSessionContext(() -> super.onMessage(message)); + } + + @Override + public void onHalfClose() { + runWithClearedSessionContext(super::onHalfClose); + } + + @Override + public void onCancel() { + runWithClearedSessionContext(super::onCancel); + } + + @Override + public void onComplete() { + runWithClearedSessionContext(super::onComplete); + } + + @Override + public void onReady() { + runWithClearedSessionContext(super::onReady); + } + }; + } + + private static void runWithClearedSessionContext(Runnable callback) { + SessionContext.clear(); + try { + callback.run(); + } finally { + SessionContext.clear(); + } + } } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java index a8387b25f2..c0bd131abf 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java @@ -1,14 +1,18 @@ package unit.net.firedevops.firemud.common.security; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.Empty; +import io.grpc.Context; +import io.grpc.Contexts; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.ServerCall; import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.Status; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @@ -92,6 +96,266 @@ void clearsStaleThreadLocalContextBeforeUnauthenticatedMethodHandler() { assertThat(SessionContext.getGlobalRoles()).isEmpty(); } + @Test + void clearsStaleThreadLocalBeforeExemptDispatchAndEveryListenerCallback() { + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + List callerContextObserved = new ArrayList<>(); + ServerCallHandler next = + new ServerCallHandler<>() { + @Override + public Listener startCall(ServerCall serverCall, Metadata headers) { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + return new Listener<>() { + @Override + public void onMessage(Empty message) { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onHalfClose() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onReady() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onComplete() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onCancel() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + }; + } + }; + + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + seedStaleCallerContext(); + + Listener listener = interceptor.interceptCall(call, new Metadata(), next); + + assertThat(callerContextObserved).containsExactly(false); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onMessage(Empty.getDefaultInstance()); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onHalfClose(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onReady(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onComplete(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + Listener cancelListener = interceptor.interceptCall(call, new Metadata(), next); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + cancelListener.onCancel(); + + assertThat(callerContextObserved) + .containsExactly(false, false, false, false, false, false, false); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(SessionContext.getAccountId()).isNull(); + } + + @Test + void clearsThreadLocalAfterEveryExemptCallbackThrows() { + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + ServerCallHandler next = + (serverCall, headers) -> + new Listener<>() { + @Override + public void onMessage(Empty message) { + throwAfterSeedingStaleContext(); + } + + @Override + public void onHalfClose() { + throwAfterSeedingStaleContext(); + } + + @Override + public void onCancel() { + throwAfterSeedingStaleContext(); + } + + @Override + public void onComplete() { + throwAfterSeedingStaleContext(); + } + + @Override + public void onReady() { + throwAfterSeedingStaleContext(); + } + }; + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + Listener listener = interceptor.interceptCall(call, new Metadata(), next); + List callbacks = + List.of( + () -> listener.onMessage(Empty.getDefaultInstance()), + listener::onHalfClose, + listener::onCancel, + listener::onComplete, + listener::onReady); + + for (Runnable callback : callbacks) { + assertThatThrownBy(callback::run) + .isInstanceOf(IllegalStateException.class) + .hasMessage("listener callback failed"); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(SessionContext.getAccountId()).isNull(); + } + } + + @Test + void preservesAuthenticatedGrpcCallerAndPeerContextForExemptReceiverGuard() { + AuthTokenInterceptor jwtInterceptor = new AuthTokenInterceptor(jwtUtil); + AuthTokenInterceptor exemptInterceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + Context.Key peerContextKey = Context.key("test-peer-context"); + String peerContextValue = "account-peer-context-preserved"; + AtomicReference accountObservedAtStart = new AtomicReference<>(); + AtomicReference peerObservedAtStart = new AtomicReference<>(); + AtomicBoolean callerContextObservedAtStart = new AtomicBoolean(false); + AtomicReference accountObservedInCallback = new AtomicReference<>(); + AtomicReference peerObservedInCallback = new AtomicReference<>(); + AtomicBoolean callerContextObservedInCallback = new AtomicBoolean(false); + ServerCallHandler receiver = + new ServerCallHandler<>() { + @Override + public Listener startCall(ServerCall serverCall, Metadata headers) { + accountObservedAtStart.set(SessionContext.getAccountId()); + peerObservedAtStart.set(peerContextKey.get()); + callerContextObservedAtStart.set(SessionContext.hasAuthenticatedCallerContext()); + SessionContext.setContext("start-poison", List.of("platformAdmin"), Map.of()); + return new Listener<>() { + @Override + public void onHalfClose() { + accountObservedInCallback.set(SessionContext.getAccountId()); + peerObservedInCallback.set(peerContextKey.get()); + callerContextObservedInCallback.set(SessionContext.hasAuthenticatedCallerContext()); + SessionContext.setContext("callback-poison", List.of("platformAdmin"), Map.of()); + } + }; + } + }; + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + + Metadata headers = new Metadata(); + String token = + jwtUtil.generateToken( + "trusted-account", + Map.of( + "accountId", "42", + "globalRoles", List.of(), + "scopedRoles", Map.of())); + headers.put(AUTH_HEADER, "Bearer " + token); + seedStaleCallerContext(); + Context peerContext = Context.current().withValue(peerContextKey, peerContextValue); + Listener listener = + Contexts.interceptCall( + peerContext, + call, + headers, + (peerCall, peerHeaders) -> + jwtInterceptor.interceptCall( + peerCall, + peerHeaders, + (authenticatedCall, authenticatedHeaders) -> + exemptInterceptor.interceptCall( + authenticatedCall, authenticatedHeaders, receiver))); + + assertThat(accountObservedAtStart).hasValue("42"); + assertThat(callerContextObservedAtStart).isTrue(); + assertThat(peerObservedAtStart).hasValue(peerContextValue); + listener.onHalfClose(); + + assertThat(accountObservedInCallback).hasValue("42"); + assertThat(callerContextObservedInCallback).isTrue(); + assertThat(peerObservedInCallback).hasValue(peerContextValue); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(SessionContext.getAccountId()).isNull(); + } + + @Test + void clearsSessionContextWhenExemptCallClosesOrStartCallFails() { + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + AtomicReference> forwardedCall = new AtomicReference<>(); + AtomicBoolean throwDuringClose = new AtomicBoolean(false); + AtomicBoolean callerContextObservedDuringClose = new AtomicBoolean(true); + ServerCallHandler next = + new ServerCallHandler<>() { + @Override + public Listener startCall(ServerCall serverCall, Metadata headers) { + forwardedCall.set(serverCall); + return new Listener<>() {}; + } + }; + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + Mockito.doAnswer( + invocation -> { + callerContextObservedDuringClose.set(SessionContext.hasAuthenticatedCallerContext()); + seedStaleCallerContext(); + if (throwDuringClose.get()) throw new IllegalStateException("failed close"); + return null; + }) + .when(call) + .close(Mockito.any(Status.class), Mockito.any(Metadata.class)); + + interceptor.interceptCall(call, new Metadata(), next); + seedStaleCallerContext(); + forwardedCall.get().close(Status.OK, new Metadata()); + + assertThat(callerContextObservedDuringClose).isFalse(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + throwDuringClose.set(true); + seedStaleCallerContext(); + assertThatThrownBy(() -> forwardedCall.get().close(Status.INTERNAL, new Metadata())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("failed close"); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + + seedStaleCallerContext(); + assertThatThrownBy( + () -> + interceptor.interceptCall( + call, + new Metadata(), + (serverCall, headers) -> { + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + throw new IllegalStateException("failed startCall"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("failed startCall"); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + @Test void clearingStaleThreadLocalContextPreservesAnExistingGrpcJwtContext() { AuthTokenInterceptor jwtInterceptor = new AuthTokenInterceptor(jwtUtil); @@ -264,6 +528,21 @@ private void seedThreadLocalInternalServiceState() { "", java.util.List.of(), Map.of(), true, "seeded-service", "seeded-instance"); } + private void seedStaleCallerContext() { + SessionContext.setContext("stale-account", List.of("platformAdmin"), Map.of()); + } + + private boolean recordCallerContextAndSeedThreadLocal() { + boolean callerContextPresent = SessionContext.hasAuthenticatedCallerContext(); + seedStaleCallerContext(); + return callerContextPresent; + } + + private void throwAfterSeedingStaleContext() { + seedStaleCallerContext(); + throw new IllegalStateException("listener callback failed"); + } + private Metadata internalServiceHeaders() { Metadata headers = new Metadata(); String token = From 2ae4e36bca8aefd9a23976bb9f46b7f27ace5335 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:24:15 +1300 Subject: [PATCH 11/22] test: verify public auth configuration through lifecycle wrapper --- .../CommonSecurityAutoConfigurationTest.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java index dca3029a7b..1c636a5c21 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java @@ -125,12 +125,23 @@ void configuredPublicMethodsBypassBearerRequirement() { ServerCallHandler next = Mockito.mock(ServerCallHandler.class); MethodDescriptor methodDescriptor = unaryMethod("demo.Service/Ping"); Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); - Mockito.when(next.startCall(Mockito.eq(call), Mockito.any(Metadata.class))) + Mockito.when( + next.startCall( + Mockito.any(ServerCall.class), Mockito.any(Metadata.class))) .thenReturn(new ServerCall.Listener<>() {}); interceptor.interceptCall(call, new Metadata(), next); - Mockito.verify(next).startCall(Mockito.eq(call), Mockito.any(Metadata.class)); + ArgumentCaptor forwardedCallCaptor = + ArgumentCaptor.forClass(ServerCall.class); + Mockito.verify(next) + .startCall(forwardedCallCaptor.capture(), Mockito.any(Metadata.class)); + ServerCall forwardedCall = forwardedCallCaptor.getValue(); + assertThat(forwardedCall).isNotSameAs(call); + assertThat(forwardedCall.getMethodDescriptor()).isSameAs(methodDescriptor); + + forwardedCall.close(Status.OK, new Metadata()); + Mockito.verify(call).close(Mockito.eq(Status.OK), Mockito.any(Metadata.class)); }); } From a8020c092d81f5ffbe008298fdb3c25c248f05a5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:25:22 +1300 Subject: [PATCH 12/22] style: apply canonical public auth fixture formatting --- .../common/config/CommonSecurityAutoConfigurationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java index 1c636a5c21..cc932124fa 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java @@ -126,8 +126,7 @@ void configuredPublicMethodsBypassBearerRequirement() { MethodDescriptor methodDescriptor = unaryMethod("demo.Service/Ping"); Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); Mockito.when( - next.startCall( - Mockito.any(ServerCall.class), Mockito.any(Metadata.class))) + next.startCall(Mockito.any(ServerCall.class), Mockito.any(Metadata.class))) .thenReturn(new ServerCall.Listener<>() {}); interceptor.interceptCall(call, new Metadata(), next); From b8f346284ace3a7845067a02826a2d65d3cb1c5e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:47:05 +1300 Subject: [PATCH 13/22] fix: correct intake review evidence and transport fixture roles --- design/project-management/ai-observations.md | 10 +++--- .../player-access-and-session.md | 2 +- ...GameLogicIntakeSettlementReadGrpcTest.java | 32 ++++++++++--------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 87d2b63622..16f3fefecd 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -144,12 +144,14 @@ Entry format: - Observation: The observer reported that the heads had no source validation. Their original source workflows later completed change detection and started the build/test matrices. No missing-source CI defect or cancellation was established; the premature report sent unnecessary investigation to Overseer. - Expected pattern: Retain each original run and classify source selection as pending or unknown while discovery or queue admission is incomplete. A completed metadata gate establishes neither source success nor source absence. The report and observer guidance were corrected with the exact source run identities. -- 2026-10-17 — Targeted Controller status can exhaust its deadline on older queue history. - - Observation: `firemud-controller --worker-identity Gameplay reviews status --pr 3224 --json` failed at its 120-second deadline during `target_history_pr_2846_cli`, after eighty prior phases consumed 119.6 seconds. It returned no JSON, delaying current front readiness readback even though publication and direct head/base verification succeeded. +- `2026-10-17`: Targeted Controller status can exhaust its deadline on older queue history + - Context: Current-front readiness readback followed publication and successful direct head/base verification. + - Observation: `firemud-controller --worker-identity Gameplay reviews status --pr 3224 --json` failed at its 120-second deadline during `target_history_pr_2846_cli`, after eighty prior phases consumed 119.6 seconds. It returned no JSON, delaying current-front readiness readback. - Expected pattern: Keep current-target status bounded while retaining historical review evidence. Overseer received the exact diagnostic; no state deletion, quota reset or installed-runtime bypass was used. The subsequent exact-checkpoint ancestry reconciliations succeeded; the failed status invocation itself remains unavailable evidence. -- 2026-10-17 — Repeated Hosted capture can reject a previously finalized provider comment. - - Observation: Admission of #3231’s second Hosted review reported a nonblocking `predecessor_terminal_capture` warning for its already-finalized first review: `Hosted finding comment contains unmarked content after its final cr-comment:v1 marker`. The original seven findings, accepted-fix records and checkpoint 6214527024 had already been recorded; the next request posted successfully as trigger 6214841384. The exact trailing-content cause remains unverified. +- `2026-10-17`: Repeated Hosted capture can reject a previously finalized provider comment + - Context: #3231’s second Hosted review was admitted after the first review had been finalized. + - Observation: Admission reported a nonblocking `predecessor_terminal_capture` warning for the finalized first review: `Hosted finding comment contains unmarked content after its final cr-comment:v1 marker`. The original seven findings, accepted-fix records and checkpoint 6214527024 had already been recorded; the next request posted successfully as trigger 6214841384. The exact trailing-content cause remains unverified. - Expected pattern: Preserve completed review evidence and surface the exact capture incompatibility without silently replacing counts or requiring a quota reset. Overseer received the retained diagnostic; Gameplay made no database or installed-runtime bypass. - `2026-10-17`: Verify every requested test class when combining Gradle selectors diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ae2a88d69b..053ee88365 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The prepared Account source adds standalone Game Logic intake authorization, an immutable source-read reservation, exact finalized recovery, authorization reads, source reads and terminal settlement. It requires the same-namespace Game Design workload and current Account creator/environment evidence for fresh work. The actual selected Game Design source read precedes Account finalization; settlement independently reads the exact Game Logic terminal before Account SQL. Retained finalized recovery uses the original request and credential hash and never resumes a fresh source read. Common typed models, protobuf codecs and authenticated clients carry the complete immutable binding. The existing Account V95–V97 storage remains unchanged; these owners add no registration, route, enabling configuration or new SQL migration. -Local qualification passes the Account check/static/format and all five focused PostgreSQL cases on the canonical PostgreSQL 18 image: 1,414 Account units have no failures or errors and four known skips; native cases have no failures, errors or skips. The namespace proof uses actual Account reservation/finalization and retained original scope, refuses cross-namespace HELD, terminal dispatch, settlement and replay, and preserves six intake tables including row metadata. R3 Common proof executes 630 cases with one oversized large-wire fixture failure; the other 625 cases outside that five-case class remain passing at R3. After correcting the bounded fixture, R5 freshly passes all five mTLS client cases and full Common static/format checks in 43s, including an actual response above the default 4MiB limit and within the 24MiB transport bound. R6 receives the published World preparation parent and passes the focused Account check/static/format, intake unit/native, Common compilation and documentation gate in 1m43s. All five native cases execute freshly without failures, errors or skips; unchanged broad units retain R3 attribution. Published CI and review remain separate. The native Account fixture controls the upstream ORIGINAL AUTHOR readback; it does not prove genuine authoring, the Game Logic retention pipeline or end-to-end settlement. The actual Game Logic intake owner and Game Design receipt pipeline are the next dependency, followed by selected launch-descriptor production. This prerequisite closes no genuine Gameplay handoff and does not resume Unit 1B/corpus. Canonical authority remains in [Account API contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); the receiving source consequence is recorded in [Gameplay Rules](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-intake-prerequisite). +Local qualification passes the Account check/static/format and all five focused PostgreSQL cases on the canonical PostgreSQL 18 image: 1,414 Account units have no failures or errors and four known skips; native cases have no failures, errors or skips. The namespace proof uses actual Account reservation/finalization and retained original scope, refuses cross-namespace HELD, terminal dispatch, settlement and replay, and preserves six intake tables including row metadata. R3 Common proof executes 630 cases with one oversized large-wire fixture failure; the other 625 cases outside that five-case class remain passing at R3. After correcting the bounded fixture, R5 freshly passes all five mTLS client cases and full Common static/format checks in 43s, including an actual response above the default 4MiB limit and within the 24MiB transport bound. R6 receives the published World preparation parent and passes the focused Account check/static/format, intake unit/native, Common compilation and documentation gate in 1m43s. All five native cases execute freshly without failures, errors or skips; unchanged broad units retain R3 attribution. Published CI and review remain separate. The native Account fixture controls the upstream ORIGINAL AUTHOR readback; it does not prove genuine authoring, the Game Logic retention pipeline or end-to-end settlement. The actual Game Logic intake owner and Game Design receipt pipeline are the next dependency, followed by selected launch-descriptor production. This prerequisite closes no genuine Gameplay handoff and does not resume Unit 1B/corpus. At this source checkpoint, the selected Game Logic intake target contract is not yet specified in the canonical [Game Logic API contracts](../../architecture/microservices/game-logic-service/api-contracts.md) or [runtime and data](../../architecture/microservices/game-logic-service/runtime-and-data.md). The [Account API contracts](../../architecture/microservices/account-service/api-contracts.md) describe only the prepared source’s Account-local unregistered consequences; [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) concerns operator ingress, not intake authority. The receiving source consequence is recorded in [Gameplay Rules](./gameplay-rules-entities-and-effects.md#selected-gameplay-rule-intake-prerequisite). Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java index fa86e95a08..b3971824d3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -52,9 +52,10 @@ /** Structural and actual loopback-mTLS proof for the closed Account settlement transport. */ class AccountGameLogicIntakeSettlementReadGrpcTest { private static final String NAMESPACE = "test"; - private static final String GL_URI = "spiffe://firemud/ns/test/sa/account-service"; - private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/game-design-service"; - private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_SERVER_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String GAME_DESIGN_CLIENT_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; private static final String STORE_PASSWORD = "test-only-store-password"; private static final int LARGE_SOURCE_ENTRIES = 1800; @@ -239,7 +240,7 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) client = new GrpcAccountGameLogicIntakeSettlementReadClient( endpoints, - pki.clientProperties(tempDirectory, pki.accountClient()), + pki.clientProperties(tempDirectory, pki.gameDesignClient()), new GrpcChannelFactory(), NAMESPACE); var evidence = evidence("test", 1, Outcome.ABORTED); @@ -277,8 +278,8 @@ void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispat throws Exception { var large = evidence("test", LARGE_SOURCE_ENTRIES, Outcome.RETAINED); assertThat(large.receipt().canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); - startServer(pki.gameLogicServer(), large); - client = newClient(server, pki.accountClient()); + startServer(pki.accountServer(), large); + client = newClient(server, pki.gameDesignClient()); client.init(); var actual = client.read(large.request()); assertThat(actual.receipt().canonicalBytes()).isEqualTo(large.receipt().canonicalBytes()); @@ -286,7 +287,7 @@ void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispat assertThat(bodies).hasValue(1); stopTransport(); startServer(pki.wrongServer(), large); - client = newClient(server, pki.accountClient()); + client = newClient(server, pki.gameDesignClient()); client.init(); assertThatThrownBy(() -> client.read(large.request())) .isInstanceOf(StatusRuntimeException.class) @@ -316,7 +317,7 @@ public void settleGameLogicIntake( SettleGameLogicIntakeRequest wire, StreamObserver observer) { bodies.incrementAndGet(); - assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_DESIGN_CLIENT_URI); var request = AccountGameLogicIntakeSettlementProtoCodec.fromRequest(wire); var response = AccountGameLogicIntakeSettlementProtoCodec.toResponse( @@ -490,9 +491,9 @@ private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) private record TestPki( X509Certificate caCertificate, - TestIdentity gameLogicServer, + TestIdentity accountServer, TestIdentity wrongServer, - TestIdentity accountClient) { + TestIdentity gameDesignClient) { private static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("terminal-test-ca.p12"); runKeytool( @@ -536,21 +537,22 @@ private static TestPki create(Path directory) throws Exception { var caCertificate = readCertificate(caFile); return new TestPki( caCertificate, - issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), - issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), - issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_SERVER_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), + issueIdentity( + directory, caStore, caFile, "game-design-client", GAME_DESIGN_CLIENT_URI, false)); } private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) throws Exception { Path certificate = writePem( - directory.resolve("account-client.crt"), + directory.resolve("game-design-client.crt"), "CERTIFICATE", identity.certificate().getEncoded()); Path privateKey = writePem( - directory.resolve("account-client.key"), + directory.resolve("game-design-client.key"), "PRIVATE KEY", identity.privateKey().getEncoded()); Path caFile = From 9225295135a4047a8695674c4e9f89519b5d1413 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 21:14:28 +1300 Subject: [PATCH 14/22] fix(gameplay): label source permission clients and test peers accurately --- .../GrpcGameLogicIntakeSourceReadClient.java | 18 +++++------ ...IntakeAuthorizationReadClientMtlsTest.java | 4 +-- ...ameLogicIntakeSourceReadTransportTest.java | 32 +++++++++---------- ...ogicIntakeAuthorizationClientMtlsTest.java | 24 +++++++------- 4 files changed, 39 insertions(+), 39 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java index 1fe404d664..3291fa62f0 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java @@ -46,11 +46,11 @@ public GrpcGameLogicIntakeSourceReadClient( public synchronized void init() throws SSLException, IOException { if (closed) - throw new IllegalStateException("Account GL intake authorization read client is closed"); + throw new IllegalStateException("Account GL intake source permission client is closed"); if (initialized) return; initReloadingClient(); if (stub() == null) - throw new IllegalStateException("Account GL intake authorization read stub unavailable"); + throw new IllegalStateException("Account GL intake source permission stub unavailable"); initialized = true; } @@ -66,7 +66,7 @@ public GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence. Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( - "Account GL intake authorization read must use the configured workload namespace"); + "Account GL intake source permission must use the configured workload namespace"); } var stub = requireStub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); @@ -119,7 +119,7 @@ public void close() throws IOException { var currentStub = stub(); if (closed || !initialized || currentStub == null) { throw new IllegalStateException( - "Account GL intake authorization read client is not initialized and available"); + "Account GL intake source permission client is not initialized and available"); } return currentStub; } @@ -128,7 +128,7 @@ private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { if (tlsProperties == null || tlsProperties.isPlaintext()) { throw new IllegalArgumentException( - "Account GL intake authorization read requires workload mTLS"); + "Account GL intake source permission requires workload mTLS"); } requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); requireReadableFile(tlsProperties.getPrivateKey(), "private key"); @@ -139,23 +139,23 @@ private static CommonGrpcClientProperties requireFileBackedMtls( private static void requireReadableFile(String configuredPath, String label) { if (configuredPath == null || configuredPath.isBlank()) { throw new IllegalArgumentException( - "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + "Account GL intake source permission requires file-backed certificate, key, and CA material"); } String pathText = configuredPath.trim(); if (pathText.startsWith("classpath:")) { throw new IllegalArgumentException( - "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + "Account GL intake source permission requires file-backed certificate, key, and CA material"); } Path path; try { path = Path.of(pathText); } catch (RuntimeException invalid) { throw new IllegalArgumentException( - "Account GL intake authorization read " + label + " must be a file-backed path", invalid); + "Account GL intake source permission " + label + " must be a file-backed path", invalid); } if (!Files.isRegularFile(path) || !Files.isReadable(path)) { throw new IllegalArgumentException( - "Account GL intake authorization read " + label + " must be an existing readable file"); + "Account GL intake source permission " + label + " must be an existing readable file"); } } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java index 9df7ff93c7..934b1a7ed4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -89,7 +89,7 @@ void readsLargeExactHeldBindingOverPinnedLoopbackMtls() throws Exception { .isGreaterThan(4 * 1024 * 1024) .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); - start(pki.gameLogicServer()); + start(pki.accountServer()); client = newClient(gameLogicClient()); client.init(); var actual = client.read(expectedRequest); @@ -109,7 +109,7 @@ void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { assertThat(calls).hasValue(0); close(); - start(pki.gameLogicServer()); + start(pki.accountServer()); client = newClient(otherCaller()); client.init(); assertThatThrownBy(() -> client.read(request)) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index 4dd282fe2c..fc32807d78 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -135,14 +135,14 @@ void roundTripsBothClosedProofsAndRejectsChangedEchoAndUnknownOrAbsentProof() { @Test void pinsAccountServerAndAuthenticatedGdClientForBothMethods() throws Exception { - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); for (var request : requests()) assertThat(client.read(request).request()).isEqualTo(request); assertThat(calls).hasValue(2); close(); start(pki.wrongServer()); - client = newClient(pki.accountClient()); + client = newClient(pki.gameDesignClient()); client.init(); assertThatThrownBy(() -> client.read(requests().getFirst())) .isInstanceOf(StatusRuntimeException.class); @@ -167,8 +167,8 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); var original = requests().getFirst(); var otherNamespace = @@ -197,8 +197,8 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) @Test void boundsUnavailableReadByDeadline() throws Exception { stall = true; - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); assertThatThrownBy(() -> client.read(requests().getFirst())) .isInstanceOf(StatusRuntimeException.class) @@ -210,7 +210,7 @@ void boundsUnavailableReadByDeadline() throws Exception { @Test void rejectsOtherAuthenticatedClientWorkload() throws Exception { - start(pki.gameLogicServer()); + start(pki.accountServer()); var wrongClient = TestPki.issueIdentity( tempDirectory, @@ -262,8 +262,8 @@ void transportsResponsesOverFourMiBWithinBothExplicitWireBudgets() throws Except assertThat(GameLogicIntakeSourceReadProtoCodec.toResponse(permission).getSerializedSize()) .isGreaterThan(4 * 1024 * 1024) .isLessThanOrEqualTo(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES); - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); assertThat(client.read(permission).request().proof().canonicalBytes()) .containsExactly(large.canonicalBytes()); @@ -534,9 +534,9 @@ record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} record TestPki( X509Certificate caCertificate, - TestIdentity gameLogicServer, + TestIdentity accountServer, TestIdentity wrongServer, - TestIdentity accountClient) { + TestIdentity gameDesignClient) { static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("terminal-test-ca.p12"); runKeytool( @@ -580,21 +580,21 @@ static TestPki create(Path directory) throws Exception { var caCertificate = readCertificate(caFile); return new TestPki( caCertificate, - issueIdentity(directory, caStore, caFile, "game-logic-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), - issueIdentity(directory, caStore, caFile, "account-client", GD_URI, false)); + issueIdentity(directory, caStore, caFile, "game-design-client", GD_URI, false)); } CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) throws Exception { Path certificate = writePem( - directory.resolve("account-client.crt"), + directory.resolve("workload-client.crt"), "CERTIFICATE", identity.certificate().getEncoded()); Path privateKey = writePem( - directory.resolve("account-client.key"), + directory.resolve("workload-client.key"), "PRIVATE KEY", identity.privateKey().getEncoded()); Path caFile = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 6c6a2e02ff..6d22814e50 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -80,8 +80,8 @@ void closeTransport() throws Exception { @Test void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws Exception { - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); var request = request(selected(1)); var authorized = client.authorize(request, CREDENTIAL); @@ -103,14 +103,14 @@ void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws E @Test void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws Exception { start(pki.wrongServer()); - client = newClient(pki.accountClient()); + client = newClient(pki.gameDesignClient()); client.init(); assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(0); closeTransport(); - start(pki.gameLogicServer()); + start(pki.accountServer()); var wrongClient = GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( tempDirectory, @@ -132,8 +132,8 @@ void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws @Test void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); var original = request(selected(1)); var wrongNamespace = @@ -152,8 +152,8 @@ void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { closeTransport(); stall = true; - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) .isInstanceOf(StatusRuntimeException.class) @@ -201,8 +201,8 @@ void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit assertThat(response.getSerializedSize()) .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); authorizeResponseOverride = response; - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); var actual = client.authorize(largeRequest, CREDENTIAL); assertThat(actual.authorization().orElseThrow().canonicalBytes()) @@ -215,8 +215,8 @@ void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit @Test void rejectsMalformedCreatorCredentialsBeforeRpcAndSanitizesMalformedEvidence() throws Exception { - start(pki.gameLogicServer()); - client = newClient(pki.accountClient()); + start(pki.accountServer()); + client = newClient(pki.gameDesignClient()); client.init(); var request = request(selected(1)); for (String malformed : List.of(" ", "x".repeat(16385))) { From 84c13074694456ea70bdb3449b6eaacb1792fa7a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:34:40 +1300 Subject: [PATCH 15/22] test(gamelogic): reuse shared client watcher lifecycle fixture --- .../GameLogicIntakeTerminalReadGrpcTest.java | 73 ++----------------- 1 file changed, 6 insertions(+), 67 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java index 0ef151aa99..e3a0b247f4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -1,5 +1,10 @@ package net.firedevops.firemud.common.gamelogic; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitBlockedReloadCallback; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitCondition; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.awaitLatch; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.setWatcher; +import static net.firedevops.firemud.common.testing.ReloadingGrpcClientWatcherTestFixture.watcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -26,7 +31,6 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; -import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -48,7 +52,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BooleanSupplier; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -141,7 +144,6 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( AbstractReloadingBlockingGrpcClient clientUnderTest = client; originalWatcher = watcher(client); - Set activeCallbacks = activeCallbacks(originalWatcher); TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); TlsCertificateWatcher delegatedWatcher = originalWatcher; doAnswer( @@ -186,7 +188,7 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); - Thread callback = awaitBlockedReloadCallback(activeCallbacks); + Thread callback = awaitBlockedReloadCallback(originalWatcher); assertThat(callback).isNotNull(); releaseClientMonitor.countDown(); @@ -824,69 +826,6 @@ ClientHandle create( } } - private static Thread awaitBlockedReloadCallback(Set activeCallbacks) - throws InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (System.nanoTime() < deadline) { - for (Thread callback : activeCallbacks) { - if (callback.getState() == Thread.State.BLOCKED - && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { - return callback; - } - } - Thread.sleep(10); - } - return null; - } - - private static boolean hasFrame(Thread thread, String className, String methodName) { - for (StackTraceElement frame : thread.getStackTrace()) { - if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { - return true; - } - } - return false; - } - - private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (!condition.getAsBoolean() && System.nanoTime() < deadline) { - Thread.sleep(10); - } - assertThat(condition.getAsBoolean()).isTrue(); - } - - private static void awaitLatch(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - } - - private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) - throws ReflectiveOperationException { - Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); - field.setAccessible(true); - return (TlsCertificateWatcher) field.get(client); - } - - private static void setWatcher( - AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) - throws ReflectiveOperationException { - Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); - field.setAccessible(true); - field.set(client, watcher); - } - - @SuppressWarnings("unchecked") - private static Set activeCallbacks(TlsCertificateWatcher watcher) - throws ReflectiveOperationException { - Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); - field.setAccessible(true); - return (Set) field.get(watcher); - } - private static void restoreReloadPolicy(String previousPolicy) { if (previousPolicy == null) { System.clearProperty(TLS_RELOAD_PROPERTY); From 2c6d53bce663206caa4cd7976772fa0af5d47339 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:46:14 +1300 Subject: [PATCH 16/22] style(gamelogic): remove obsolete watcher helper import --- .../common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java index e3a0b247f4..34e4520eea 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -45,7 +45,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; From 60de76c4aa5286a0fd72c777ee184868c8f5afc3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 03:36:17 +1300 Subject: [PATCH 17/22] Reuse intake client lifecycle policy and distinguish permanent refusals --- design/project-management/ai-observations.md | 2 + ...meLogicIntakeAuthorizationGrpcService.java | 3 +- ...gicIntakeAuthorizationGrpcServiceTest.java | 23 +++++ ...ameLogicIntakeAuthorizationReadClient.java | 83 ++---------------- .../GameLogicIntakeTerminalReadClient.java | 81 ++--------------- .../GameplayRuleSourceReadClient.java | 86 ++----------------- ...ntGameLogicIntakeSettlementReadClient.java | 81 ++--------------- ...rpcGameLogicIntakeAuthorizationClient.java | 63 ++------------ .../GrpcGameLogicIntakeRetainClient.java | 80 ++--------------- .../GrpcGameLogicIntakeSourceReadClient.java | 85 +++--------------- .../AbstractReloadingBlockingGrpcClient.java | 8 ++ 11 files changed, 97 insertions(+), 498 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 545f29b209..557b54db52 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -152,11 +152,13 @@ Entry format: - Context: Current-front readiness readback followed publication and successful direct head/base verification. - Observation: `firemud-controller --worker-identity Gameplay reviews status --pr 3224 --json` failed at its 120-second deadline during `target_history_pr_2846_cli`, after eighty prior phases consumed 119.6 seconds. It returned no JSON, delaying current-front readiness readback. - Expected pattern: Keep current-target status bounded while retaining historical review evidence. Overseer received the exact diagnostic; no state deletion, quota reset or installed-runtime bypass was used. The subsequent exact-checkpoint ancestry reconciliations succeeded; the failed status invocation itself remains unavailable evidence. + - Reconsideration trigger: when targeted `reviews status --pr` completes within its deadline for a PR with long queue history, or the Controller bounds historical phases separately, qualify that behavior and revisit the retained status-readback limitation. - `2026-10-17`: Repeated Hosted capture can reject a previously finalized provider comment - Context: #3231’s second Hosted review was admitted after the first review had been finalized. - Observation: Admission reported a nonblocking `predecessor_terminal_capture` warning for the finalized first review: `Hosted finding comment contains unmarked content after its final cr-comment:v1 marker`. The original seven findings, accepted-fix records and checkpoint 6214527024 had already been recorded; the next request posted successfully as trigger 6214841384. The exact trailing-content cause remains unverified. - Expected pattern: Preserve completed review evidence and surface the exact capture incompatibility without silently replacing counts or requiring a quota reset. Overseer received the retained diagnostic; Gameplay made no database or installed-runtime bypass. + - Reconsideration trigger: when the trailing-content cause after the final `cr-comment:v1` marker is identified, or a repeated capture of the affected finalized predecessor completes without the warning, verify the outcome and revisit this retained capture limitation. - `2026-10-18`: Expose review-allocation decision provenance beside its remaining budget - Context: #3233 had three lifetime Hosted results while the current native selector correctly showed a separate additional allowance with zero of two used. A retained handover incorrectly inferred exhaustion from the lifetime total. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java index 3b72c49cca..904c0bb50d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java @@ -246,7 +246,8 @@ private Status peerDenial() { private static Status statusOf(RuntimeException error) { if (error instanceof StatusRuntimeException status) return Status.fromCode(status.getStatus().getCode()); - if (error instanceof IllegalArgumentException) return Status.FAILED_PRECONDITION; + if (error instanceof IllegalArgumentException || error instanceof IllegalStateException) + return Status.FAILED_PRECONDITION; return Status.UNAVAILABLE; } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java index 60ba413179..d105b4e257 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java @@ -211,6 +211,29 @@ void reportsOwnerFailuresBySanitizedStatusAndNeverEchoesCredential() { assertThat(denied.error().getCause()).isNull(); } + @Test + void distinguishesPermanentOwnerRefusalsFromStorageOutages() { + var failures = + List.of( + Map.entry(new IllegalStateException(CREDENTIAL), Status.Code.FAILED_PRECONDITION), + Map.entry(new IllegalArgumentException(CREDENTIAL), Status.Code.FAILED_PRECONDITION), + Map.entry( + new org.springframework.dao.DataAccessResourceFailureException(CREDENTIAL), + Status.Code.UNAVAILABLE), + Map.entry( + new org.springframework.transaction.CannotCreateTransactionException(CREDENTIAL), + Status.Code.UNAVAILABLE)); + for (var failure : failures) { + org.mockito.Mockito.doThrow(failure.getKey()) + .when(owner) + .authorizeWithEnvironmentCapture(eq(CREDENTIAL), any(), any(), any()); + var result = authorized(() -> invokeAuthorize(request())); + assertThat(result.code()).isEqualTo(failure.getValue()); + assertThat(result.error().toString()).doesNotContain(CREDENTIAL); + assertThat(result.error().getCause()).isNull(); + } + } + private record Result(GameLogicIntakeAuthorizationResponse response, Throwable error) { Status.Code code() { return Status.fromThrowable(error).getCode(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java index 19168fa1b3..ba3783904e 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,6 +9,7 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -26,8 +25,6 @@ public final class GameLogicIntakeAuthorizationReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GameLogicIntakeAuthorizationReadClient( ServiceEndpointsProperties endpoints, @@ -36,7 +33,7 @@ public GameLogicIntakeAuthorizationReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Account GL intake authorization read"), channelFactory, GameLogicIntakeAuthorizationReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -45,31 +42,24 @@ public GameLogicIntakeAuthorizationReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) - throw new IllegalStateException("Account GL intake authorization read client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account GL intake authorization read stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account GL intake authorization read client is closed", + "Account GL intake authorization read stub unavailable"); } /** Returns a validated HELD result only after exact Account server mTLS identity verification. */ public GameLogicIntakeAuthorizationReadEvidence read( GameLogicIntakeAuthorizationReadEvidence.Request request) { - if (org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive() - || org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - throw new IllegalStateException("Account intake transport must run outside SQL"); + requireNoAmbientSql("Account intake transport must run outside SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Account GL intake authorization read must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Account GL intake authorization read client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readHeldGameLogicIntakeAuthorization( GameLogicIntakeAuthorizationReadGrpcCodec.toRequest(request)); @@ -101,59 +91,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountGameLogicIntakeAuthorizationReadServiceGrpc - .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Account GL intake authorization read client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException( - "Account GL intake authorization read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Account GL intake authorization read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Account GL intake authorization read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Account GL intake authorization read " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Account GL intake authorization read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java index f5b4b72071..b9c0cb9104 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -24,8 +23,6 @@ public final class GameLogicIntakeTerminalReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GameLogicIntakeTerminalReadClient( ServiceEndpointsProperties endpoints, @@ -34,7 +31,7 @@ public GameLogicIntakeTerminalReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Game Logic intake terminal read"), channelFactory, GameLogicIntakeTerminalReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -43,13 +40,10 @@ public GameLogicIntakeTerminalReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Game Logic intake terminal read client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Game Logic intake terminal read stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Game Logic intake terminal read client is closed", + "Game Logic intake terminal read stub unavailable"); } /** @@ -58,18 +52,15 @@ public synchronized void init() throws SSLException, IOException { */ public GameLogicIntakeTerminalReadEvidence read( GameLogicIntakeTerminalReadEvidence.Request request) { - if (org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive() - || org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - throw new IllegalStateException("Game Logic terminal transport must run outside SQL"); + requireNoAmbientSql("Game Logic terminal transport must run outside SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Game Logic intake terminal read must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Game Logic intake terminal read client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readGameplayRuleIntakeTerminal( GameLogicIntakeTerminalReadGrpcCodec.toRequest(request)); @@ -101,58 +92,4 @@ protected String defaultTarget() { .withMaxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private GameLogicGameplayRuleIntakeTerminalReadServiceGrpc - .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Game Logic intake terminal read client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Game Logic intake terminal read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Game Logic intake terminal read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Game Logic intake terminal read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Game Logic intake terminal read " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Game Logic intake terminal read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java index 75f541879d..ea246e3bf4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -24,8 +23,6 @@ public final class GameplayRuleSourceReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GameplayRuleSourceReadClient( ServiceEndpointsProperties endpoints, @@ -34,7 +31,7 @@ public GameplayRuleSourceReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Game Design complete gameplay source read"), channelFactory, GameplayRuleSourceReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -43,30 +40,23 @@ public GameplayRuleSourceReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) - throw new IllegalStateException("Game Design complete gameplay source read client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Game Design complete gameplay source read stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Game Design complete gameplay source read client is closed", + "Game Design complete gameplay source read stub unavailable"); } /** Returns exact source evidence only after Game Design server mTLS identity verification. */ public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Request request) { - if (org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive() - || org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - throw new IllegalStateException("GD source transport must run outside SQL"); + requireNoAmbientSql("GD source transport must run outside SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Game Design complete gameplay source read must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Game Design complete gameplay source read client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readSelectedGameplayRuleSource(GameplayRuleSourceReadGrpcCodec.toRequest(request)); try { @@ -98,62 +88,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private GameDesignGameplayRuleSourceReadServiceGrpc - .GameDesignGameplayRuleSourceReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Game Design complete gameplay source read client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException( - "Game Design complete gameplay source read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Game Design complete gameplay source read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Game Design complete gameplay source read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Game Design complete gameplay source read " + label + " must be a file-backed path", - invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Game Design complete gameplay source read " - + label - + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java index 2a6b1f4fbd..f42df27c1a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,6 +9,7 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -25,8 +24,6 @@ public final class GrpcAccountGameLogicIntakeSettlementReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcAccountGameLogicIntakeSettlementReadClient( ServiceEndpointsProperties endpoints, @@ -35,7 +32,7 @@ public GrpcAccountGameLogicIntakeSettlementReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Account intake settlement read"), channelFactory, GrpcAccountGameLogicIntakeSettlementReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -44,13 +41,10 @@ public GrpcAccountGameLogicIntakeSettlementReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Account intake settlement read client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account intake settlement read stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account intake settlement read client is closed", + "Account intake settlement read stub unavailable"); } /** @@ -59,18 +53,15 @@ public synchronized void init() throws SSLException, IOException { @Override public AccountGameLogicIntakeSettlementReadEvidence read( AccountGameLogicIntakeSettlementReadEvidence.Request request) { - if (org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive() - || org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - throw new IllegalStateException("Account settlement transport must run outside SQL"); + requireNoAmbientSql("Account settlement transport must run outside SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Account intake settlement read must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Account intake settlement read client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .settleGameLogicIntake(AccountGameLogicIntakeSettlementProtoCodec.toRequest(request)); try { @@ -101,58 +92,4 @@ protected String defaultTarget() { .withMaxInboundMessageSize(AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountGameLogicIntakeSettlementServiceGrpc - .AccountGameLogicIntakeSettlementServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Account intake settlement read client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Account intake settlement read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Account intake settlement read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Account intake settlement read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Account intake settlement read " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Account intake settlement read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java index ee3e455191..697dd179a2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java @@ -5,8 +5,6 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -14,11 +12,11 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** File-backed mTLS client for the standalone, unregistered Account intake producer. */ public final class GrpcGameLogicIntakeAuthorizationClient @@ -29,8 +27,6 @@ public final class GrpcGameLogicIntakeAuthorizationClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcGameLogicIntakeAuthorizationClient( ServiceEndpointsProperties endpoints, @@ -39,7 +35,7 @@ public GrpcGameLogicIntakeAuthorizationClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Account intake authorization"), channelFactory, GrpcGameLogicIntakeAuthorizationClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) @@ -47,13 +43,10 @@ public GrpcGameLogicIntakeAuthorizationClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Account intake authorization client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account intake authorization stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account intake authorization client is closed", + "Account intake authorization stub unavailable"); } @Override @@ -78,15 +71,11 @@ private GameLogicIntakeAuthorizationEvidence.Result invoke( GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential, Operation operation) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) - throw new IllegalStateException("Account intake authorization requires no ambient SQL"); + requireNoAmbientSql("Account intake authorization requires no ambient SQL"); Objects.requireNonNull(request); if (!workloadNamespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Account intake authorization namespace mismatch"); - var current = stub(); - if (closed || !initialized || current == null) - throw new IllegalStateException("Account intake authorization client unavailable"); + var current = requireInitializedStub("Account intake authorization client unavailable"); var credentials = credentials(originalCreatorCredential, operation); var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); try { @@ -153,42 +142,6 @@ protected String defaultTarget() { .withCompression("gzip"); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) - throw new IllegalArgumentException("Account intake authorization requires workload mTLS"); - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null - || configuredPath.isBlank() - || configuredPath.trim().startsWith("classpath:")) - throw new IllegalArgumentException( - "Account intake authorization requires file-backed certificate, key, and CA material"); - Path path; - try { - path = Path.of(configuredPath.trim()); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException("Invalid Account intake authorization " + label + " path"); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) - throw new IllegalArgumentException( - "Account intake authorization " + label + " must be an existing readable file"); - } - private enum Operation { AUTHORIZE, RECOVER, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java index 6f29847fb2..3310988261 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java @@ -2,14 +2,13 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -24,8 +23,6 @@ public final class GrpcGameLogicIntakeRetainClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcGameLogicIntakeRetainClient( ServiceEndpointsProperties endpoints, @@ -34,7 +31,7 @@ public GrpcGameLogicIntakeRetainClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Game Logic intake retain"), channelFactory, GrpcGameLogicIntakeRetainClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -43,31 +40,21 @@ public GrpcGameLogicIntakeRetainClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Game Logic intake retain client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Game Logic intake retain stub unavailable"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Game Logic intake retain client is closed", "Game Logic intake retain stub unavailable"); } @Override public GameLogicIntakeRetainEvidence retain(GameLogicIntakeRetainEvidence.Request request) { - if (org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive() - || org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) { - throw new IllegalStateException("Game Logic intake retain transport must run outside SQL"); - } + requireNoAmbientSql("Game Logic intake retain transport must run outside SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Game Logic intake retain must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub("Game Logic intake retain client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .retainGameplayRuleIntake(GameLogicIntakeRetainProtoCodec.toRequest(request)); try { @@ -98,57 +85,4 @@ protected String defaultTarget() { .withMaxInboundMessageSize(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Game Logic intake retain client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Game Logic intake retain requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Game Logic intake retain requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Game Logic intake retain requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Game Logic intake retain " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Game Logic intake retain " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java index 3291fa62f0..f6982db838 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -11,6 +9,7 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedMtls; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -25,8 +24,6 @@ public final class GrpcGameLogicIntakeSourceReadClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GrpcGameLogicIntakeSourceReadClient( ServiceEndpointsProperties endpoints, @@ -35,7 +32,7 @@ public GrpcGameLogicIntakeSourceReadClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + FileBackedMtls.require(tlsProperties, "Account GL intake source permission"), channelFactory, GrpcGameLogicIntakeSourceReadClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -44,31 +41,26 @@ public GrpcGameLogicIntakeSourceReadClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) - throw new IllegalStateException("Account GL intake source permission client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account GL intake source permission stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account GL intake source permission client is closed", + "Account GL intake source permission stub unavailable"); } /** * Returns exact source permission confirmation after Account server mTLS identity verification. */ public GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence.Request request) { - if (org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive() - || org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - throw new IllegalStateException("Account intake transport must run outside SQL"); + requireNoAmbientSql("Account intake transport must run outside SQL"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Account GL intake source permission must use the configured workload namespace"); } - var stub = requireStub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var stub = + requireInitializedStub( + "Account GL intake source permission client is not initialized and available") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); var response = request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary @@ -103,59 +95,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountGameLogicIntakeSourceReadServiceGrpc - .AccountGameLogicIntakeSourceReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Account GL intake source permission client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException( - "Account GL intake source permission requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Account GL intake source permission requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Account GL intake source permission requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Account GL intake source permission " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Account GL intake source permission " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 48459e3340..4e2f8cd6a6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import org.slf4j.Logger; +import org.springframework.transaction.support.TransactionSynchronizationManager; public abstract class AbstractReloadingBlockingGrpcClient> implements AutoCloseable { @@ -45,6 +46,13 @@ protected AbstractReloadingBlockingGrpcClient( this.logger = LoggingUtil.getLogger(loggerClass); } + protected static final void requireNoAmbientSql(String message) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException(message); + } + } + protected final void initReloadingClient() throws SSLException, IOException { if (tlsProps.isPlaintext() || !GrpcTlsReloadPolicy.isEnabled()) { reloadChannel(); From bc25e7b0a5b86e40efda5adad9ddbbe38bdaa2fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 04:10:29 +1300 Subject: [PATCH 18/22] Share intake TLS test fixtures and document receiver limits --- .../account-service/api-contracts.md | 2 +- ...GameLogicIntakeSettlementReadGrpcTest.java | 255 +------------- ...IntakeAuthorizationReadClientMtlsTest.java | 49 +-- ...ameLogicIntakeSourceReadTransportTest.java | 286 ++------------- .../GameLogicIntakeTerminalReadGrpcTest.java | 252 +------------- ...ogicIntakeAuthorizationClientMtlsTest.java | 49 +-- ...pcGameLogicIntakeRetainClientMtlsTest.java | 252 +------------- .../common/gamelogic/IntakeTestPki.java | 328 ++++++++++++++++++ 8 files changed, 456 insertions(+), 1017 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/IntakeTestPki.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a31eb60b3f..66e8c718c3 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling a standalone HELD-read server, its receiving limit must allow the existing `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES` request bound; this is a required receiver configuration, not a claim about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. +The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`, `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`, or `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java index b3971824d3..197bbb3f8a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -17,17 +17,10 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; -import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Base64; import java.util.EnumMap; import java.util.List; import java.util.Map; @@ -56,11 +49,10 @@ class AccountGameLogicIntakeSettlementReadGrpcTest { private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; private static final String GAME_DESIGN_CLIENT_URI = "spiffe://firemud/ns/test/sa/game-design-service"; - private static final String STORE_PASSWORD = "test-only-store-password"; private static final int LARGE_SOURCE_ENTRIES = 1800; @TempDir static Path tempDirectory; - private static TestPki pki; + private static IntakeTestPki pki; private Server server; private GrpcAccountGameLogicIntakeSettlementReadClient client; private AtomicInteger headers; @@ -68,7 +60,14 @@ class AccountGameLogicIntakeSettlementReadGrpcTest { @BeforeAll static void createTrustedCertificates() throws Exception { - pki = TestPki.create(tempDirectory); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("account-server", ACCOUNT_SERVER_URI), + IntakeTestPki.IdentitySpec.server("wrong-server", WRONG_SERVER_URI), + IntakeTestPki.IdentitySpec.client("game-design-client", GAME_DESIGN_CLIENT_URI)); } @AfterEach @@ -240,7 +239,7 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) client = new GrpcAccountGameLogicIntakeSettlementReadClient( endpoints, - pki.clientProperties(tempDirectory, pki.gameDesignClient()), + pki.clientProperties(tempDirectory, pki.client()), new GrpcChannelFactory(), NAMESPACE); var evidence = evidence("test", 1, Outcome.ABORTED); @@ -278,8 +277,8 @@ void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispat throws Exception { var large = evidence("test", LARGE_SOURCE_ENTRIES, Outcome.RETAINED); assertThat(large.receipt().canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); - startServer(pki.accountServer(), large); - client = newClient(server, pki.gameDesignClient()); + startServer(pki.server(), large); + client = newClient(server, pki.client()); client.init(); var actual = client.read(large.request()); assertThat(actual.receipt().canonicalBytes()).isEqualTo(large.receipt().canonicalBytes()); @@ -287,7 +286,7 @@ void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispat assertThat(bodies).hasValue(1); stopTransport(); startServer(pki.wrongServer(), large); - client = newClient(server, pki.gameDesignClient()); + client = newClient(server, pki.client()); client.init(); assertThatThrownBy(() -> client.read(large.request())) .isInstanceOf(StatusRuntimeException.class) @@ -305,7 +304,7 @@ private enum Outcome { } private void startServer( - TestIdentity identity, AccountGameLogicIntakeSettlementReadEvidence evidence) + IntakeTestPki.Identity identity, AccountGameLogicIntakeSettlementReadEvidence evidence) throws Exception { headers = new AtomicInteger(); bodies = new AtomicInteger(); @@ -354,7 +353,7 @@ service, countHeaders, new GrpcPeerIdentityInterceptor())) } private GrpcAccountGameLogicIntakeSettlementReadClient newClient( - Server target, TestIdentity local) throws Exception { + Server target, IntakeTestPki.Identity local) throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + target.getPort()); return new GrpcAccountGameLogicIntakeSettlementReadClient( @@ -486,228 +485,4 @@ private static AccountGameLogicIntakeSettlementReadEvidence evidence( AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization), new AccountGameLogicIntakeSettlementEvidence(terminal)); } - - private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} - - private record TestPki( - X509Certificate caCertificate, - TestIdentity accountServer, - TestIdentity wrongServer, - TestIdentity gameDesignClient) { - private static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("terminal-test-ca.p12"); - runKeytool( - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD terminal-read test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("terminal-test-ca.crt"); - runKeytool( - "-exportcert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - var caCertificate = readCertificate(caFile); - return new TestPki( - caCertificate, - issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_SERVER_URI, true), - issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), - issueIdentity( - directory, caStore, caFile, "game-design-client", GAME_DESIGN_CLIENT_URI, false)); - } - - private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) - throws Exception { - Path certificate = - writePem( - directory.resolve("game-design-client.crt"), - "CERTIFICATE", - identity.certificate().getEncoded()); - Path privateKey = - writePem( - directory.resolve("game-design-client.key"), - "PRIVATE KEY", - identity.privateKey().getEncoded()); - Path caFile = - writePem( - directory.resolve("terminal-client-ca.crt"), - "CERTIFICATE", - caCertificate.getEncoded()); - var properties = new CommonGrpcClientProperties(); - properties.setCertChain(certificate.toString()); - properties.setPrivateKey(privateKey.toString()); - properties.setCaCert(caFile.toString()); - return properties; - } - - private static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) - throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + ".crt"); - String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; - runKeytool( - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - runKeytool( - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - runKeytool( - "-gencert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san); - runKeytool( - "-importcert", - "-alias", - "test-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - runKeytool( - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - var command = new ArrayList(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("keytool failed: " + output); - } - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } - } - - private static Path writePem(Path path, String label, byte[] bytes) throws IOException { - String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); - return Files.writeString( - path, - "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", - StandardCharsets.US_ASCII); - } - } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java index 934b1a7ed4..85c76edd4f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -42,8 +42,8 @@ class GameLogicIntakeAuthorizationReadClientMtlsTest { private static final int MAX_BINDING_BYTES = 4 * 1024 * 1024; @TempDir static Path tempDirectory; - private static GameLogicIntakeSourceReadTransportTest.TestPki pki; - private static GameLogicIntakeSourceReadTransportTest.TestIdentity gameLogicClientIdentity; + private static IntakeTestPki pki; + private static IntakeTestPki.Identity gameLogicClientIdentity; private Server server; private GameLogicIntakeAuthorizationReadClient client; private GameLogicIntakeAuthorizationReadEvidence.Request expectedRequest; @@ -51,7 +51,16 @@ class GameLogicIntakeAuthorizationReadClientMtlsTest { @BeforeAll static void certificates() throws Exception { - pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("account-server", ACCOUNT_URI), + IntakeTestPki.IdentitySpec.server( + "wrong-server", "spiffe://firemud/ns/test/sa/game-logic-service"), + IntakeTestPki.IdentitySpec.client( + "game-design-client", "spiffe://firemud/ns/test/sa/game-design-service")); gameLogicClientIdentity = issueIdentity("game-logic-client", GAME_LOGIC_URI); } @@ -89,7 +98,7 @@ void readsLargeExactHeldBindingOverPinnedLoopbackMtls() throws Exception { .isGreaterThan(4 * 1024 * 1024) .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); - start(pki.accountServer()); + start(pki.server()); client = newClient(gameLogicClient()); client.init(); var actual = client.read(expectedRequest); @@ -109,7 +118,7 @@ void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { assertThat(calls).hasValue(0); close(); - start(pki.accountServer()); + start(pki.server()); client = newClient(otherCaller()); client.init(); assertThatThrownBy(() -> client.read(request)) @@ -121,8 +130,7 @@ void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { assertThat(calls).hasValue(0); } - private void start(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) - throws Exception { + private void start(IntakeTestPki.Identity identity) throws Exception { var service = new AccountGameLogicIntakeAuthorizationReadServiceGrpc .AccountGameLogicIntakeAuthorizationReadServiceImplBase() { @@ -155,8 +163,8 @@ public void readHeldGameLogicIntakeAuthorization( .start(); } - private GameLogicIntakeAuthorizationReadClient newClient( - GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + private GameLogicIntakeAuthorizationReadClient newClient(IntakeTestPki.Identity identity) + throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); return new GameLogicIntakeAuthorizationReadClient( @@ -166,26 +174,21 @@ private GameLogicIntakeAuthorizationReadClient newClient( NAMESPACE); } - private GameLogicIntakeSourceReadTransportTest.TestIdentity gameLogicClient() throws Exception { + private IntakeTestPki.Identity gameLogicClient() throws Exception { return gameLogicClientIdentity; } - private static GameLogicIntakeSourceReadTransportTest.TestIdentity issueIdentity( - String alias, String workloadUri) throws Exception { - return GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( - tempDirectory, - tempDirectory.resolve("terminal-test-ca.p12"), - tempDirectory.resolve("terminal-test-ca.crt"), - alias, - workloadUri, - false); + private static IntakeTestPki.Identity issueIdentity(String alias, String workloadUri) + throws Exception { + return IntakeTestPki.issueIdentity( + tempDirectory, pki.caKeyStore(), pki.caCertificateFile(), alias, workloadUri, false); } - private GameLogicIntakeSourceReadTransportTest.TestIdentity otherCaller() throws Exception { - return GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + private IntakeTestPki.Identity otherCaller() throws Exception { + return IntakeTestPki.issueIdentity( tempDirectory, - tempDirectory.resolve("terminal-test-ca.p12"), - tempDirectory.resolve("terminal-test-ca.crt"), + pki.caKeyStore(), + pki.caCertificateFile(), "other-client", "spiffe://firemud/ns/test/sa/game-design-service", false); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index fc32807d78..8c974627e3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -12,17 +12,9 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; -import java.io.IOException; import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Base64; import java.util.EnumMap; import java.util.List; import java.util.Map; @@ -50,9 +42,8 @@ class GameLogicIntakeSourceReadTransportTest { private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; - private static final String STORE_PASSWORD = "test-only-store-password"; @TempDir static Path tempDirectory; - private static TestPki pki; + private static IntakeTestPki pki; private Server server; private GrpcGameLogicIntakeSourceReadClient client; private final AtomicInteger calls = new AtomicInteger(); @@ -61,7 +52,14 @@ class GameLogicIntakeSourceReadTransportTest { @BeforeAll static void certificates() throws Exception { - pki = TestPki.create(tempDirectory); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("account-server", ACCOUNT_URI), + IntakeTestPki.IdentitySpec.server("wrong-server", WRONG_SERVER_URI), + IntakeTestPki.IdentitySpec.client("game-design-client", GD_URI)); } @AfterEach @@ -135,14 +133,14 @@ void roundTripsBothClosedProofsAndRejectsChangedEchoAndUnknownOrAbsentProof() { @Test void pinsAccountServerAndAuthenticatedGdClientForBothMethods() throws Exception { - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); for (var request : requests()) assertThat(client.read(request).request()).isEqualTo(request); assertThat(calls).hasValue(2); close(); start(pki.wrongServer()); - client = newClient(pki.gameDesignClient()); + client = newClient(pki.client()); client.init(); assertThatThrownBy(() -> client.read(requests().getFirst())) .isInstanceOf(StatusRuntimeException.class); @@ -167,8 +165,8 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); var original = requests().getFirst(); var otherNamespace = @@ -197,8 +195,8 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) @Test void boundsUnavailableReadByDeadline() throws Exception { stall = true; - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); assertThatThrownBy(() -> client.read(requests().getFirst())) .isInstanceOf(StatusRuntimeException.class) @@ -210,12 +208,12 @@ void boundsUnavailableReadByDeadline() throws Exception { @Test void rejectsOtherAuthenticatedClientWorkload() throws Exception { - start(pki.accountServer()); + start(pki.server()); var wrongClient = - TestPki.issueIdentity( + IntakeTestPki.issueIdentity( tempDirectory, - tempDirectory.resolve("terminal-test-ca.p12"), - tempDirectory.resolve("terminal-test-ca.crt"), + pki.caKeyStore(), + pki.caCertificateFile(), "wrong-source-client", ACCOUNT_URI, false); @@ -262,8 +260,8 @@ void transportsResponsesOverFourMiBWithinBothExplicitWireBudgets() throws Except assertThat(GameLogicIntakeSourceReadProtoCodec.toResponse(permission).getSerializedSize()) .isGreaterThan(4 * 1024 * 1024) .isLessThanOrEqualTo(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES); - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); assertThat(client.read(permission).request().proof().canonicalBytes()) .containsExactly(large.canonicalBytes()); @@ -275,18 +273,18 @@ void transportsResponsesOverFourMiBWithinBothExplicitWireBudgets() throws Except .isGreaterThan(4 * 1024 * 1024) .isLessThanOrEqualTo(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES); var gdServer = - TestPki.issueIdentity( + IntakeTestPki.issueIdentity( tempDirectory, - tempDirectory.resolve("terminal-test-ca.p12"), - tempDirectory.resolve("terminal-test-ca.crt"), + pki.caKeyStore(), + pki.caCertificateFile(), "source-gd-server", GD_URI, true); var glClient = - TestPki.issueIdentity( + IntakeTestPki.issueIdentity( tempDirectory, - tempDirectory.resolve("terminal-test-ca.p12"), - tempDirectory.resolve("terminal-test-ca.crt"), + pki.caKeyStore(), + pki.caCertificateFile(), "source-gl-client", "spiffe://firemud/ns/test/sa/game-logic-service", false); @@ -356,7 +354,7 @@ void rejectsEnvelopesOverExplicitWireBudgetBeforeCanonicalDecode() { .isInstanceOf(IllegalArgumentException.class); } - private void start(TestIdentity identity) throws Exception { + private void start(IntakeTestPki.Identity identity) throws Exception { var service = new AccountGameLogicIntakeSourceReadServiceGrpc .AccountGameLogicIntakeSourceReadServiceImplBase() { @@ -412,7 +410,8 @@ private void respond( .start(); } - private GrpcGameLogicIntakeSourceReadClient newClient(TestIdentity identity) throws Exception { + private GrpcGameLogicIntakeSourceReadClient newClient(IntakeTestPki.Identity identity) + throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); return new GrpcGameLogicIntakeSourceReadClient( @@ -529,227 +528,4 @@ private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding bind "revisionId", binding.revisions().getFirst().revisionId().toString()))))); } - - record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} - - record TestPki( - X509Certificate caCertificate, - TestIdentity accountServer, - TestIdentity wrongServer, - TestIdentity gameDesignClient) { - static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("terminal-test-ca.p12"); - runKeytool( - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD terminal-read test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("terminal-test-ca.crt"); - runKeytool( - "-exportcert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - var caCertificate = readCertificate(caFile); - return new TestPki( - caCertificate, - issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), - issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), - issueIdentity(directory, caStore, caFile, "game-design-client", GD_URI, false)); - } - - CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) - throws Exception { - Path certificate = - writePem( - directory.resolve("workload-client.crt"), - "CERTIFICATE", - identity.certificate().getEncoded()); - Path privateKey = - writePem( - directory.resolve("workload-client.key"), - "PRIVATE KEY", - identity.privateKey().getEncoded()); - Path caFile = - writePem( - directory.resolve("terminal-client-ca.crt"), - "CERTIFICATE", - caCertificate.getEncoded()); - var properties = new CommonGrpcClientProperties(); - properties.setCertChain(certificate.toString()); - properties.setPrivateKey(privateKey.toString()); - properties.setCaCert(caFile.toString()); - return properties; - } - - static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) - throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + ".crt"); - String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; - runKeytool( - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - runKeytool( - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - runKeytool( - "-gencert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san); - runKeytool( - "-importcert", - "-alias", - "test-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - runKeytool( - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - var command = new ArrayList(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("keytool failed: " + output); - } - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } - } - - private static Path writePem(Path path, String label, byte[] bytes) throws IOException { - String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); - return Files.writeString( - path, - "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", - StandardCharsets.US_ASCII); - } - } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java index 34e4520eea..20723c7e9e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -30,17 +30,11 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; -import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Base64; import java.util.EnumMap; import java.util.List; import java.util.Map; @@ -79,12 +73,11 @@ class GameLogicIntakeTerminalReadGrpcTest { private static final String GL_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/game-design-service"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; - private static final String STORE_PASSWORD = "test-only-store-password"; private static final int LARGE_SOURCE_ENTRIES = 1800; private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; @TempDir static Path tempDirectory; - private static TestPki pki; + private static IntakeTestPki pki; private Server server; private GameLogicIntakeTerminalReadClient client; private AtomicInteger headers; @@ -92,7 +85,14 @@ class GameLogicIntakeTerminalReadGrpcTest { @BeforeAll static void createTrustedCertificates() throws Exception { - pki = TestPki.create(tempDirectory); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("game-logic-server", GL_URI), + IntakeTestPki.IdentitySpec.server("wrong-server", WRONG_GL_URI), + IntakeTestPki.IdentitySpec.client("account-client", ACCOUNT_URI)); } @AfterEach @@ -338,8 +338,8 @@ void loopbackStrictMtlsTransportsLargeCanonicalTerminalAndPinsBothPeerIdentities assertThat(GameLogicIntakeTerminalReadGrpcCodec.toResponse(large).getSerializedSize()) .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES); - startServer(pki.gameLogicServer(), large); - client = newClient(server, pki.accountClient()); + startServer(pki.server(), large); + client = newClient(server, pki.client()); client.init(); var actual = client.read(large.request()); assertThat(actual.terminal().orElseThrow().canonicalBytes()).isEqualTo(terminalBytes); @@ -348,7 +348,7 @@ void loopbackStrictMtlsTransportsLargeCanonicalTerminalAndPinsBothPeerIdentities stopTransport(); startServer(pki.wrongServer(), large); - client = newClient(server, pki.accountClient()); + client = newClient(server, pki.client()); client.init(); assertThatThrownBy(() -> client.read(large.request())) .isInstanceOf(StatusRuntimeException.class) @@ -365,7 +365,8 @@ private enum Outcome { ABORTED } - private void startServer(TestIdentity identity, GameLogicIntakeTerminalReadEvidence evidence) + private void startServer( + IntakeTestPki.Identity identity, GameLogicIntakeTerminalReadEvidence evidence) throws Exception { headers = new AtomicInteger(); bodies = new AtomicInteger(); @@ -413,7 +414,7 @@ service, countHeaders, new GrpcPeerIdentityInterceptor())) .start(); } - private GameLogicIntakeTerminalReadClient newClient(Server target, TestIdentity local) + private GameLogicIntakeTerminalReadClient newClient(Server target, IntakeTestPki.Identity local) throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setGameLogicService("localhost:" + target.getPort()); @@ -547,229 +548,6 @@ private static GameLogicIntakeTerminalReadEvidence evidence( Optional.of(terminal)); } - private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} - - private record TestPki( - X509Certificate caCertificate, - TestIdentity gameLogicServer, - TestIdentity wrongServer, - TestIdentity accountClient) { - private static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("terminal-test-ca.p12"); - runKeytool( - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD terminal-read test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("terminal-test-ca.crt"); - runKeytool( - "-exportcert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - var caCertificate = readCertificate(caFile); - return new TestPki( - caCertificate, - issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), - issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), - issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); - } - - private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) - throws Exception { - Path certificate = - writePem( - directory.resolve("account-client.crt"), - "CERTIFICATE", - identity.certificate().getEncoded()); - Path privateKey = - writePem( - directory.resolve("account-client.key"), - "PRIVATE KEY", - identity.privateKey().getEncoded()); - Path caFile = - writePem( - directory.resolve("terminal-client-ca.crt"), - "CERTIFICATE", - caCertificate.getEncoded()); - var properties = new CommonGrpcClientProperties(); - properties.setCertChain(certificate.toString()); - properties.setPrivateKey(privateKey.toString()); - properties.setCaCert(caFile.toString()); - return properties; - } - - private static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) - throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + ".crt"); - String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; - runKeytool( - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - runKeytool( - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - runKeytool( - "-gencert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san); - runKeytool( - "-importcert", - "-alias", - "test-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - runKeytool( - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - var command = new ArrayList(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("keytool failed: " + output); - } - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } - } - - private static Path writePem(Path path, String label, byte[] bytes) throws IOException { - String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); - return Files.writeString( - path, - "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", - StandardCharsets.US_ASCII); - } - } - @FunctionalInterface private interface Initialize { void run() throws Exception; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 6d22814e50..08f00d0379 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -49,7 +49,7 @@ class GrpcGameLogicIntakeAuthorizationClientMtlsTest { private static final String CREDENTIAL = "unchanged.creator.credential"; @TempDir static Path tempDirectory; - private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private static IntakeTestPki pki; private Server server; private GrpcGameLogicIntakeAuthorizationClient client; private final AtomicInteger calls = new AtomicInteger(); @@ -61,7 +61,15 @@ class GrpcGameLogicIntakeAuthorizationClientMtlsTest { @BeforeAll static void certificates() throws Exception { - pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + pki = + IntakeTestPki.create( + tempDirectory, + "terminal", + "FireMUD terminal-read test CA", + IntakeTestPki.IdentitySpec.server("account-server", ACCOUNT_URI), + IntakeTestPki.IdentitySpec.server( + "wrong-server", "spiffe://firemud/ns/test/sa/game-logic-service"), + IntakeTestPki.IdentitySpec.client("game-design-client", GD_URI)); } @AfterEach @@ -80,8 +88,8 @@ void closeTransport() throws Exception { @Test void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws Exception { - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); var request = request(selected(1)); var authorized = client.authorize(request, CREDENTIAL); @@ -103,19 +111,19 @@ void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws E @Test void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws Exception { start(pki.wrongServer()); - client = newClient(pki.gameDesignClient()); + client = newClient(pki.client()); client.init(); assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(0); closeTransport(); - start(pki.accountServer()); + start(pki.server()); var wrongClient = - GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + IntakeTestPki.issueIdentity( tempDirectory, - tempDirectory.resolve("terminal-test-ca.p12"), - tempDirectory.resolve("terminal-test-ca.crt"), + pki.caKeyStore(), + pki.caCertificateFile(), "wrong-game-design-client", ACCOUNT_URI, false); @@ -132,8 +140,8 @@ void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws @Test void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); var original = request(selected(1)); var wrongNamespace = @@ -152,8 +160,8 @@ void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { closeTransport(); stall = true; - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) .isInstanceOf(StatusRuntimeException.class) @@ -201,8 +209,8 @@ void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit assertThat(response.getSerializedSize()) .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); authorizeResponseOverride = response; - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); var actual = client.authorize(largeRequest, CREDENTIAL); assertThat(actual.authorization().orElseThrow().canonicalBytes()) @@ -215,8 +223,8 @@ void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit @Test void rejectsMalformedCreatorCredentialsBeforeRpcAndSanitizesMalformedEvidence() throws Exception { - start(pki.accountServer()); - client = newClient(pki.gameDesignClient()); + start(pki.server()); + client = newClient(pki.client()); client.init(); var request = request(selected(1)); for (String malformed : List.of(" ", "x".repeat(16385))) { @@ -242,8 +250,7 @@ void rejectsMalformedCreatorCredentialsBeforeRpcAndSanitizesMalformedEvidence() assertThat(calls).hasValue(1); } - private void start(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) - throws Exception { + private void start(IntakeTestPki.Identity identity) throws Exception { var service = new AccountGameLogicIntakeAuthorizationServiceGrpc .AccountGameLogicIntakeAuthorizationServiceImplBase() { @@ -334,8 +341,8 @@ service, credentialInterceptor, new GrpcPeerIdentityInterceptor())) .start(); } - private GrpcGameLogicIntakeAuthorizationClient newClient( - GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + private GrpcGameLogicIntakeAuthorizationClient newClient(IntakeTestPki.Identity identity) + throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); return new GrpcGameLogicIntakeAuthorizationClient( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java index c2a6e431fb..2829ab80aa 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java @@ -12,23 +12,13 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; -import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; @@ -46,10 +36,9 @@ class GrpcGameLogicIntakeRetainClientMtlsTest { private static final String GL_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; - private static final String STORE_PASSWORD = "test-only-store-password"; @TempDir static Path tempDirectory; - private static TestPki pki; + private static IntakeTestPki pki; private Server server; private GrpcGameLogicIntakeRetainClient client; @@ -58,7 +47,14 @@ class GrpcGameLogicIntakeRetainClientMtlsTest { @BeforeAll static void createTrustedWorkloadCertificates() throws Exception { - pki = TestPki.create(tempDirectory); + pki = + IntakeTestPki.create( + tempDirectory, + "intake-retain", + "FireMUD intake-retain test CA", + IntakeTestPki.IdentitySpec.server("game-logic-server", GL_URI), + IntakeTestPki.IdentitySpec.server("wrong-server", WRONG_GL_URI), + IntakeTestPki.IdentitySpec.client("game-design-client", GD_URI)); } @AfterEach @@ -87,7 +83,7 @@ void acceptsLargeTerminalFromExactGameLogicServerAndRejectsSubstitutedServer() t byte[] expectedTerminal = terminal.canonicalBytes(); assertThat(expectedTerminal.length).isGreaterThan(4 * 1024 * 1024); - startServer(pki.gameLogicServer(), request, terminal); + startServer(pki.server(), request, terminal); client = newClient(server.getPort()); client.init(); var actual = client.retain(request); @@ -110,7 +106,7 @@ void acceptsLargeTerminalFromExactGameLogicServerAndRejectsSubstitutedServer() t } private void startServer( - TestIdentity identity, + IntakeTestPki.Identity identity, GameLogicIntakeRetainEvidence.Request expectedRequest, GameLogicGameplayRuleIntakeTerminal terminal) throws Exception { @@ -152,232 +148,8 @@ private GrpcGameLogicIntakeRetainClient newClient(int port) throws Exception { endpoints.setGameLogicService("localhost:" + port); return new GrpcGameLogicIntakeRetainClient( endpoints, - pki.clientProperties(tempDirectory, pki.gameDesignClient()), + pki.clientProperties(tempDirectory, pki.client()), new GrpcChannelFactory(), NAMESPACE); } - - private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} - - private record TestPki( - X509Certificate caCertificate, - TestIdentity gameLogicServer, - TestIdentity wrongServer, - TestIdentity gameDesignClient) { - private static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("intake-retain-test-ca.p12"); - runKeytool( - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD intake-retain test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("intake-retain-test-ca.crt"); - runKeytool( - "-exportcert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - var caCertificate = readCertificate(caFile); - return new TestPki( - caCertificate, - issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), - issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), - issueIdentity(directory, caStore, caFile, "game-design-client", GD_URI, false)); - } - - private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) - throws Exception { - Path certificate = - writePem( - directory.resolve("game-design-client.crt"), - "CERTIFICATE", - identity.certificate().getEncoded()); - Path privateKey = - writePem( - directory.resolve("game-design-client.key"), - "PRIVATE KEY", - identity.privateKey().getEncoded()); - Path caFile = - writePem( - directory.resolve("intake-retain-client-ca.crt"), - "CERTIFICATE", - caCertificate.getEncoded()); - var properties = new CommonGrpcClientProperties(); - properties.setCertChain(certificate.toString()); - properties.setPrivateKey(privateKey.toString()); - properties.setCaCert(caFile.toString()); - return properties; - } - - private static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) - throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + ".crt"); - String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; - String eku = server ? "serverAuth" : "clientAuth"; - runKeytool( - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + eku, - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - runKeytool( - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - runKeytool( - "-gencert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + eku, - "-ext", - "SAN=" + san); - runKeytool( - "-importcert", - "-alias", - "test-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - runKeytool( - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - var command = new ArrayList(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("keytool failed: " + output); - } - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } - } - - private static Path writePem(Path path, String label, byte[] bytes) throws IOException { - String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); - return Files.writeString( - path, - "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", - StandardCharsets.US_ASCII); - } - } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/IntakeTestPki.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/IntakeTestPki.java new file mode 100644 index 0000000000..91849a1171 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/IntakeTestPki.java @@ -0,0 +1,328 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; + +/** Shared loopback-mTLS PKI fixture for the gameplay-rule intake transport tests. */ +record IntakeTestPki( + X509Certificate caCertificate, + Identity server, + Identity wrongServer, + Identity client, + Path caKeyStore, + Path caCertificateFile, + String filePrefix) { + private static final String STORE_PASSWORD = "test-only-store-password"; + + record Identity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + record IdentitySpec(String alias, String workloadUri, boolean server) { + static IdentitySpec server(String alias, String workloadUri) { + return new IdentitySpec(alias, workloadUri, true); + } + + static IdentitySpec client(String alias, String workloadUri) { + return new IdentitySpec(alias, workloadUri, false); + } + } + + static IntakeTestPki create( + Path directory, + String filePrefix, + String caCommonName, + IdentitySpec server, + IdentitySpec wrongServer, + IdentitySpec client) + throws Exception { + Path caStore = directory.resolve(filePrefix + "-test-ca.p12"); + runKeytool( + directory, + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + caCommonName, + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve(filePrefix + "-test-ca.crt"); + runKeytool( + directory, + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new IntakeTestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, server), + issueIdentity(directory, caStore, caFile, wrongServer), + issueIdentity(directory, caStore, caFile, client), + caStore, + caFile, + filePrefix); + } + + CommonGrpcClientProperties clientProperties(Path directory, Identity identity) throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve(filePrefix + "-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + static Identity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + return issueIdentity(directory, caStore, caFile, new IdentitySpec(alias, workloadUri, server)); + } + + private static Identity issueIdentity( + Path directory, Path caStore, Path caFile, IdentitySpec spec) throws Exception { + String alias = spec.alias(); + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + spec.workloadUri() + ",DNS:localhost,IP:127.0.0.1"; + String eku = spec.server() ? "serverAuth" : "clientAuth"; + runKeytool( + directory, + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + directory, + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + directory, + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new Identity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(Path tempDirectory, String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile(tempDirectory, "keytool-", ".log"); + Process process = null; + boolean cleanupWaitAttempted = false; + try { + process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + cleanupWaitAttempted = true; + boolean terminated = process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException( + "keytool timed out after 30 seconds; terminated after forced stop=" + + terminated + + ": " + + readKeytoolOutput(outputFile)); + } + String output = readKeytoolOutput(outputFile); + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } catch (InterruptedException interrupted) { + if (process != null) { + process.destroyForcibly(); + cleanupWaitAttempted = true; + try { + process.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException cleanupInterrupted) { + interrupted.addSuppressed(cleanupInterrupted); + } + } + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + if (process != null && process.isAlive() && !cleanupWaitAttempted) { + process.destroyForcibly(); + try { + process.waitFor(5, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + Files.deleteIfExists(outputFile); + } + } + + private static String readKeytoolOutput(Path outputFile) throws IOException { + int maxOutputBytes = 64 * 1024; + byte[] output; + boolean truncated; + try (var stream = Files.newInputStream(outputFile)) { + output = stream.readNBytes(maxOutputBytes); + truncated = stream.read() != -1; + } + String text = new String(output, StandardCharsets.UTF_8); + return truncated ? text + "\n[keytool output truncated]" : text; + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } +} From e2034dfadabfd56eea95cdfccf369fe6585e4132 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 04:14:44 +1300 Subject: [PATCH 19/22] Keep Account identity explicit in shared intake test setup --- .../GameLogicIntakeAuthorizationReadClientMtlsTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java index 85c76edd4f..e9682baa5f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -56,7 +56,8 @@ static void certificates() throws Exception { tempDirectory, "terminal", "FireMUD terminal-read test CA", - IntakeTestPki.IdentitySpec.server("account-server", ACCOUNT_URI), + IntakeTestPki.IdentitySpec.server( + "account-server", "spiffe://firemud/ns/test/sa/account-service"), IntakeTestPki.IdentitySpec.server( "wrong-server", "spiffe://firemud/ns/test/sa/game-logic-service"), IntakeTestPki.IdentitySpec.client( From e51feea11259b5e9ab03f324fb1c964966d8ed98 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 04:56:27 +1300 Subject: [PATCH 20/22] Distinguish permanent Account intake refusals from storage outages --- ...meLogicIntakeAuthorizationReadService.java | 14 ++- ...tGameLogicIntakeSettlementGrpcService.java | 2 +- ...gicIntakeAuthorizationReadServiceTest.java | 110 ++++++++++++++++++ ...eLogicIntakeSettlementGrpcServiceTest.java | 33 +++++- 4 files changed, 148 insertions(+), 11 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadServiceTest.java diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java index d4410c83e9..e52e3279c9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java @@ -48,14 +48,20 @@ public void requireHeld(GameLogicIntakeAuthorizationReadEvidence.Request request return null; }); } catch (StatusRuntimeException failure) { - throw failure; - } catch (IllegalArgumentException changed) { - throw Status.FAILED_PRECONDITION.asRuntimeException(); + throw sanitized(Status.fromCode(failure.getStatus().getCode())); + } catch (IllegalArgumentException | IllegalStateException changed) { + throw sanitized(Status.FAILED_PRECONDITION); } catch (RuntimeException unavailable) { - throw Status.UNAVAILABLE.asRuntimeException(); + throw sanitized(Status.UNAVAILABLE); } } + private static StatusRuntimeException sanitized(Status status) { + return status + .withDescription("Account intake authorization read denied or unavailable") + .asRuntimeException(); + } + static void requirePeer(String namespace) { var peer = GrpcPeerIdentity.current(); if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java index 60d644e833..376ca21941 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java @@ -66,7 +66,7 @@ public void settleGameLogicIntake( } catch (StatusRuntimeException failure) { deny(observer, Status.fromCode(failure.getStatus().getCode())); return; - } catch (IllegalArgumentException changedPrecondition) { + } catch (IllegalArgumentException | IllegalStateException changedPrecondition) { deny(observer, Status.FAILED_PRECONDITION); return; } catch (RuntimeException unavailable) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..b4fb1cf36d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadServiceTest.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; + +class AccountGameLogicIntakeAuthorizationReadServiceTest { + private final AccountGameLogicIntakeAuthorizationRepository repository = + mock(AccountGameLogicIntakeAuthorizationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountGameLogicIntakeAuthorizationReadService service = + new AccountGameLogicIntakeAuthorizationReadService(repository, transactions, "test"); + private final GameLogicIntakeAuthorizationBinding binding = + mock(GameLogicIntakeAuthorizationBinding.class); + private final GameLogicIntakeAuthorizationReadEvidence.Request request = + mock(GameLogicIntakeAuthorizationReadEvidence.Request.class); + + @AfterEach + void clearTransactionState() { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + + @Test + void permanentOwnerRefusalsBecomeSanitizedFailedPrecondition() { + when(request.targetNamespace()).thenReturn("test"); + when(request.binding()).thenReturn(binding); + doThrow(new IllegalArgumentException("private-binding-mismatch")) + .when(repository) + .readHeld(binding, "test"); + var argumentFailure = asGameLogic(() -> service.requireHeld(request)); + assertSanitized(argumentFailure, Status.Code.FAILED_PRECONDITION, "private-binding-mismatch"); + + doThrow(new IllegalStateException("private-owner-state")) + .when(repository) + .readHeld(binding, "test"); + var stateFailure = asGameLogic(() -> service.requireHeld(request)); + assertSanitized(stateFailure, Status.Code.FAILED_PRECONDITION, "private-owner-state"); + } + + @Test + void databaseAndTransactionCreationFailuresRemainSanitizedUnavailable() { + when(request.targetNamespace()).thenReturn("test"); + when(request.binding()).thenReturn(binding); + doThrow(new DataAccessResourceFailureException("private-database-outage")) + .when(repository) + .readHeld(binding, "test"); + var databaseFailure = asGameLogic(() -> service.requireHeld(request)); + assertSanitized(databaseFailure, Status.Code.UNAVAILABLE, "private-database-outage"); + + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenThrow(new CannotCreateTransactionException("private-transaction-outage")); + var transactionFailure = asGameLogic(() -> service.requireHeld(request)); + assertSanitized(transactionFailure, Status.Code.UNAVAILABLE, "private-transaction-outage"); + } + + @Test + void preservesStatusRuntimeCodesWithSanitizedDescriptionAndNoCause() { + when(request.targetNamespace()).thenReturn("test"); + when(request.binding()).thenReturn(binding); + doThrow( + Status.PERMISSION_DENIED + .withDescription("private-owner-evidence") + .withCause(new IllegalStateException("private-cause")) + .asRuntimeException()) + .when(repository) + .readHeld(binding, "test"); + var failure = asGameLogic(() -> service.requireHeld(request)); + assertSanitized(failure, Status.Code.PERMISSION_DENIED, "private-owner-evidence"); + assertThat(failure.toString()).doesNotContain("private-cause"); + } + + private static StatusRuntimeException asGameLogic(Runnable action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()); + try { + context.run(action); + throw new AssertionError("Expected sanitized RPC status"); + } catch (StatusRuntimeException failure) { + return failure; + } + } + + private static void assertSanitized( + StatusRuntimeException failure, Status.Code code, String secret) { + assertThat(failure.getStatus().getCode()).isEqualTo(code); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Account intake authorization read denied or unavailable"); + assertThat(failure.toString()).doesNotContain(secret); + assertThat(failure.getCause()).isNull(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java index cf6c5547ad..6617d688f5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -31,6 +31,8 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Context-level transport proofs; durable settlement belongs to the owner service. */ @@ -126,11 +128,23 @@ void substitutedReceiptAndOwnerFailuresDenyWithoutLeakingDiagnostics() { doThrow(new IllegalArgumentException("private-stale-precondition")).when(owner).settle(any()); var stalePrecondition = authorized(() -> invoke(request)); assertThat(stalePrecondition.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(stalePrecondition.error().toString()).doesNotContain("private-stale-precondition"); - doThrow(new IllegalStateException("private-storage-failure")).when(owner).settle(any()); - var storageFailure = authorized(() -> invoke(request)); - assertThat(storageFailure.code()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(storageFailure.error().toString()).doesNotContain("private-storage-failure"); + assertSanitized(stalePrecondition.error(), "private-stale-precondition"); + doThrow(new IllegalStateException("private-stale-owner-state")).when(owner).settle(any()); + var staleOwnerState = authorized(() -> invoke(request)); + assertThat(staleOwnerState.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertSanitized(staleOwnerState.error(), "private-stale-owner-state"); + doThrow(new DataAccessResourceFailureException("private-database-outage")) + .when(owner) + .settle(any()); + var databaseFailure = authorized(() -> invoke(request)); + assertThat(databaseFailure.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertSanitized(databaseFailure.error(), "private-database-outage"); + doThrow(new CannotCreateTransactionException("private-transaction-outage")) + .when(owner) + .settle(any()); + var transactionFailure = authorized(() -> invoke(request)); + assertThat(transactionFailure.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertSanitized(transactionFailure.error(), "private-transaction-outage"); doThrow( Status.FAILED_PRECONDITION .withDescription("private-owner-evidence") @@ -139,7 +153,14 @@ void substitutedReceiptAndOwnerFailuresDenyWithoutLeakingDiagnostics() { .settle(any()); var failed = authorized(() -> invoke(request)); assertThat(failed.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(failed.error().toString()).doesNotContain("private-owner-evidence"); + assertSanitized(failed.error(), "private-owner-evidence"); + } + + private static void assertSanitized(Throwable error, String secret) { + assertThat(error.toString()).doesNotContain(secret); + assertThat(error.getCause()).isNull(); + assertThat(Status.fromThrowable(error).getDescription()) + .isEqualTo("Account intake settlement denied or unavailable"); } private record Result(SettleGameLogicIntakeResponse response, Throwable error) { From 36c1f6b3c5dd66515acc211463e6e57120e4a070 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 05:49:08 +1300 Subject: [PATCH 21/22] fix: qualify maximum intake creator metadata transport --- .../account-service/api-contracts.md | 2 +- ...meLogicIntakeAuthorizationCredentials.java | 4 +++ ...ogicIntakeAuthorizationClientMtlsTest.java | 31 +++++++++++-------- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 66e8c718c3..6b6eb5a045 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`, `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`, or `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. +The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`, `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`, or `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java index 7742adfc40..f317de09de 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java @@ -12,6 +12,10 @@ /** Method-scoped protected metadata for the unchanged original creator credential. */ public final class AccountGameLogicIntakeAuthorizationCredentials { public static final int MAX_CREDENTIAL_BYTES = 16384; + + /** Base64 binary metadata plus bounded gRPC metadata overhead for the maximum credential. */ + public static final int MAX_METADATA_BYTES = ((MAX_CREDENTIAL_BYTES + 2) / 3) * 4 + 1024; + public static final Context.Key CONTEXT_KEY = Context.key("account-game-logic-intake-original-creator"); public static final Metadata.Key HEADER = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 08f00d0379..7fa474ef0e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -22,9 +22,9 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; @@ -53,9 +53,9 @@ class GrpcGameLogicIntakeAuthorizationClientMtlsTest { private Server server; private GrpcGameLogicIntakeAuthorizationClient client; private final AtomicInteger calls = new AtomicInteger(); - private final AtomicReference callerPeer = new AtomicReference<>(); - private final AtomicReference observedCredential = new AtomicReference<>(); - private final AtomicReference observedMethod = new AtomicReference<>(); + private final List observedCredentials = new CopyOnWriteArrayList<>(); + private final List observedMethods = new CopyOnWriteArrayList<>(); + private final List observedPeers = new CopyOnWriteArrayList<>(); private volatile GameLogicIntakeAuthorizationResponse authorizeResponseOverride; private volatile boolean stall; @@ -92,20 +92,23 @@ void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws E client = newClient(pki.client()); client.init(); var request = request(selected(1)); - var authorized = client.authorize(request, CREDENTIAL); + String maximumCredential = + "x".repeat(AccountGameLogicIntakeAuthorizationCredentials.MAX_CREDENTIAL_BYTES); + var authorized = client.authorize(request, maximumCredential); assertThat(authorized.outcome()) .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); assertThat(authorized.authorization().orElseThrow().intakeRequestId()) .isEqualTo(request.intakeRequestId()); - var recovered = client.recover(request, CREDENTIAL); + var recovered = client.recover(request, maximumCredential); assertThat(recovered.outcome()) .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); - var aborted = client.abort(request, CREDENTIAL); + var aborted = client.abort(request, maximumCredential); assertThat(aborted.outcome()).isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); assertThat(calls).hasValue(3); - assertThat(callerPeer).hasValue(GD_URI); - assertThat(observedCredential).hasValue(CREDENTIAL); - assertThat(observedMethod.get()).contains("AbortIntake"); + assertThat(observedPeers).containsExactly(GD_URI, GD_URI, GD_URI); + assertThat(observedCredentials) + .containsExactly(maximumCredential, maximumCredential, maximumCredential); + assertThat(observedMethods).containsExactly("AuthorizeIntake", "RecoverIntake", "AbortIntake"); } @Test @@ -280,9 +283,9 @@ private void respond( StreamObserver observer, String method) { calls.incrementAndGet(); - observedMethod.set(method); - callerPeer.set(GrpcPeerIdentity.current().uri()); - observedCredential.set( + observedMethods.add(method); + observedPeers.add(GrpcPeerIdentity.current().uri()); + observedCredentials.add( AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get().value()); assertThat(Context.current().getDeadline()).isNotNull(); if (stall) return; @@ -328,6 +331,8 @@ public io.grpc.ServerCall.Listener interceptCall( server = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .maxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) + .maxInboundMetadataSize( + AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES) .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) From e3a2eb0c539b027f99731ac8a7fc97db1e342d4b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 06:05:08 +1300 Subject: [PATCH 22/22] docs: identify every standalone intake receiver message bound --- .../architecture/microservices/account-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 6b6eb5a045..b46729aa03 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`, `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`, or `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. +The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: authorization and HELD read use `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`; source read uses `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`; settlement uses `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates.