From 1d54fc3ae28834c53df532895b395f9f64204180 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:38:43 +1300 Subject: [PATCH 1/3] Extract authenticated authored-world source and intake foundation --- .../game-design-service/api-contracts.md | 12 +- .../world-management-service/api-contracts.md | 10 + ...ame-authoring-publishing-and-activation.md | 6 + .../world-runtime-and-movement.md | 6 + .../v1/tenant_identity_service.proto | 27 + .../v1/world_management_service.proto | 62 + ...GrpcServerPeerIdentityCallCredentials.java | 41 + .../tenant/AuthoredWorldSourceClient.java | 158 ++ .../tenant/AuthoredWorldSourceDigest.java | 147 ++ .../tenant/AuthoredWorldSourceEvidence.java | 63 + .../tenant/AuthoredWorldSourceGrpcCodec.java | 115 ++ .../WorldAuthoredSourceIntakeClient.java | 178 +++ .../WorldAuthoredSourceIntakeGrpcCodec.java | 307 ++++ .../tenant/AuthoredWorldSourceClientTest.java | 134 ++ .../AuthoredWorldSourceEvidenceTest.java | 398 +++++ .../AuthoredWorldSourceGrpcCodecTest.java | 154 ++ .../WorldAuthoredSourceIntakeClientTest.java | 296 ++++ ...orldAuthoredSourceIntakeGrpcCodecTest.java | 242 +++ services/game-design-service/build.gradle.kts | 3 + ...AuthoredWorldSourceDeliveryRepository.java | 604 ++++++++ .../GameAuthoredWorldSourceRepository.java | 469 ++++++ .../impl/TenantIdentityGrpcService.java | 115 +- .../src/main/resources/application-prod.yml | 1 + .../src/main/resources/application.yml | 1 + ...34.1__authored_world_source_operations.sql | 224 +++ .../V34.2__world_authored_source_delivery.sql | 249 +++ ...redWorldSourceDeliveryIntegrationTest.java | 624 ++++++++ ...dWorldSourceRepositoryIntegrationTest.java | 617 ++++++++ .../TenantIdentityGrpcAuthWiringTest.java | 230 ++- .../impl/AuthoredWorldSourceMtlsTest.java | 861 +++++++++++ .../GameSessionTenantAssociationGrpcTest.java | 4 +- .../impl/TenantIdentityGrpcServiceTest.java | 241 ++- .../world-management-service/build.gradle.kts | 3 + ...orldAuthoredSourceIntakeConfiguration.java | 86 ++ .../WorldAuthoredSourceIntakeDigest.java | 112 ++ .../WorldAuthoredSourceIntakeGrpcService.java | 265 ++++ .../WorldAuthoredSourceIntakeReceipt.java | 61 + .../WorldAuthoredSourceIntakeRepository.java | 629 ++++++++ .../WorldAuthoredSourceIntakeService.java | 336 +++++ .../src/main/resources/application.yml | 3 + .../V23.1__world_authored_source_intake.sql | 250 ++++ ..._world_canonical_tenant_mutation_guard.sql | 219 +++ ...ldAuthoredSourceIntakeIntegrationTest.java | 1329 +++++++++++++++++ ...thoredSourceIntakeMtlsIntegrationTest.java | 661 ++++++++ ...AuthoredSourceIntakeConfigurationTest.java | 159 ++ .../WorldAuthoredSourceIntakeDigestTest.java | 131 ++ ...ldAuthoredSourceIntakeGrpcServiceTest.java | 438 ++++++ .../WorldAuthoredSourceIntakeMtlsTest.java | 695 +++++++++ .../WorldAuthoredSourceIntakeServiceTest.java | 638 ++++++++ 49 files changed, 12594 insertions(+), 20 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V34.2__world_authored_source_delivery.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfiguration.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfigurationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 18ef917cc2..2b224c73a8 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -20,6 +20,16 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e `GameTenantCreationRepository.createCandidate` is an owner-local transaction primitive, not a tenant-creation API. There is no creation RPC or authenticated creator authority in this slice, so normal creator-facing tenant creation remains unavailable. This boundary must not be used as an admin shortcut, an Account JOIN substitute, or proof that any Account association or runtime admission is enabled. +## Authored-world source evidence and World delivery + +Game Design owns the persisted authored-world selector association. `tenantSlug` identifies its tenant selector; `worldSlug` is a separate tenant-scoped selector. Neither a matching slug nor a private numeric row key proves another owner's tenant association. An immutable source registration binds `targetNamespace`, stable `registrationRequestId`, canonical tenant UUID, `tenantSlug`, `worldSlug`, and `worldDisplayName`; its receipt additionally binds the allocated source `operationId`, request digest, exact Game Design row/key provenance, and evidence digest. Exact retries replay that receipt; changed input under the same identity conflicts rather than resolving another source. + +`TenantIdentityService.ResolveAuthoredWorldSource` is a read-only lookup for the exact same-namespace Game Session or World Management mTLS peer. Its closed request contains `requestId`, `operationId`, `canonicalTenantId`, and `worldSlug`; IDs are canonical nonnil UUIDs. It returns the complete persisted v1 source receipt and echoes the read identity. Missing, ambiguous, malformed, unknown-field, wrong-peer, wrong-namespace, or mismatched evidence fails closed. `AuthoredWorldSourceDigest` defines separate `game-design-authored-world-source-request/v1` and `game-design-authored-world-source-receipt/v1` SHA-256 domains using the byte-length framing owned by `GameTenantCreationDigest`; consumers validate the complete tuple and digest, not just the selector. + +Fresh `NEW_GAME_ROW` source registration commits its immutable delivery claim in the same Game Design transaction. The claim retains a stable World intake identity, complete source evidence, and expected intake digest. An acknowledgement must match the exact authenticated World receipt; retries preserve the original claim and committed result. A retry does not repair a missing historical delivery claim. Retained source associations require their separate audited owner evidence and do not enter this fresh-delivery path. Normal delivery is automatic rather than an operator association step; World owns the receiver and its private association under [authored-world source intake](../world-management-service/api-contracts.md#authored-world-source-intake). + +Source registration and delivery are identity prerequisites only: they do not authorize creator mutations, attest a published release, create a Game Session catalog entry, or authorize runtime admission. The [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#authored-world-source-foundation) records the bounded repository/readback implementation, missing automatic dispatcher and creator-facing wiring, and unexecuted PostgreSQL and runtime proof. + ## Official Hosted Creator Mutation Gate For official hosted deployments, every creator-intent content-bearing mutation enters the Game Design boundary only after the Account-owned currentness/evidence authority in [Account Service API Contracts](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) has been evaluated for the tenant's Creator Party, identified operator, and hosted-terms scope under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). This applies before the first persisted Draft and before later authoring/revision, asset, template, plugin, and publication writes. The acting account's current tenant authorization is a separate conjunct; Gateway/UI checks are advisory. @@ -126,7 +136,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e The only permitted peer is the verified Game Session workload identity `spiffe://firemud/ns/{namespace}/sa/game-session-service`, where `{namespace}` must exactly match Game Design's configured `FIREMUD_GRPC_WORKLOAD_NAMESPACE`. An empty or invalid configured namespace, absent verified peer identity, another service identity, or a peer from another namespace returns `PERMISSION_DENIED`. JWT claims and request metadata are not peer identity; workload authentication follows [Authentication and Authorization](../../system-architecture-authentication.md). -The shared `AuthTokenInterceptor` configuration exempts exactly the full RPC method names `TenantIdentityService/ResolveRuntimeTenantIdentity`, `TenantIdentityService/ResolveLegacyGameSessionTenantAssociation`, `TenantIdentityService/ResolvePublishedRealmEntryPolicy`, and `TenantIdentityService/ListPublishedRealmEntryPolicies` from bearer-token validation because these are workload-only methods under [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). This is not public transport exposure: the gRPC listener still requires mTLS, and each handler requires the exact verified workload identity above. No other Game Design RPC is exempted. +The shared `AuthTokenInterceptor` configuration exempts only the explicitly listed full method names for workload-only reads under [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md): `TenantIdentityService/ResolveRuntimeTenantIdentity`, `TenantIdentityService/ResolveLegacyGameSessionTenantAssociation`, `TenantIdentityService/ResolvePublishedRealmEntryPolicy`, `TenantIdentityService/ListPublishedRealmEntryPolicies`, `TenantIdentityService/ResolveFreshTenantCreation`, and `TenantIdentityService/ResolveAuthoredWorldSource`. This is not public transport exposure: the gRPC listener still requires mTLS, and each handler enforces its own exact peer and namespace contract. The fresh-creation and authored-source reads have the distinct caller sets defined in their owner sections above; the runtime identity read permits only Game Session. No other Game Design RPC is exempted. The request contains exactly two fields: `canonical_tenant_id` and `request_id`, each a canonical lower-case, nonnil UUID string. Unknown protobuf fields, noncanonical/nil IDs, or a missing ID return `INVALID_ARGUMENT`. The tenant UUID is only a selector: Game Design returns it only after an exact canonical-UUID lookup and owner-row provenance validation. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 340b01d865..f1b11ec5a2 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -11,6 +11,16 @@ This API contract is target-state canonical; implementation coverage is partial - The current typed `ApplyWorldDesignMutation` owner-write boundary also has no method/workload or tenant authorization beyond shared JWT parsing: its gRPC handler forwards any authenticated bearer to the mutation service, whose current checks cover request shape and Draft state but not caller identity or tenant access. This is separate from the digest-read gap and the legacy REST generation-rule gap; the target authenticated Game Design caller and tenant authorization remain defined by the design-time contract below, and wrong-workload/cross-tenant denial is not implemented or proved. - Required executable migration/proof gate: `./gradlew :world-management-service:test :game-logic-service:test :game-session-service:test :tcp-proxy-service:crossServiceTest`. This gate must update the bridge, callers, examples, and checked-in proof together and pass before the target examples below may be treated as current. This document does not claim that the gate exists or passes. +## Authored-world source intake + +Fresh World content enters through authenticated [Game Design authored-source evidence](../game-design-service/api-contracts.md#authored-world-source-evidence-and-world-delivery), not inferred tenant ownership. The separate `WorldAuthoredSourceIntakeService` accepts only the verified same-namespace Game Design mTLS peer. `IntakeAuthoredWorldSource` binds the closed v1 tuple `{schemaVersion, targetNamespace, intakeRequestId, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest}`. Workload identity authenticates the owner handoff; it does not supply creator or runtime authorization. + +For an uncommitted intake, World obtains and validates the exact fresh Game Design source receipt before its local transaction. World then commits the complete source evidence, local canonical-UUID-to-private-key association, and immutable intake receipt together. It reads the exact result back after commit before reporting success. Existing exact retries replay the durable receipt without reallocating identity or resolving a replacement source; changed binding under the same request fails closed. Private numeric World keys remain internal. Retained or contradictory rows cannot use this fresh intake: they require a separate owner-approved, audited association with exact retained-row evidence, never Account's manifest or guessed numeric/slug equality. + +`ReadAuthoredWorldSourceIntake` accepts the complete original intake binding plus a distinct nonnil `requestId` for the read. It returns only an exact committed receipt, echoes both identities and the full binding, and never allocates state or repeats the Game Design source read. The request digest uses the versioned `world-authored-source-intake-request/v1` byte-framed SHA-256 preimage; the receipt digest is an authenticated World attestation that also binds its private association and is not client-recomputable. Callers verify the response binding and recomputable request digest while treating the receipt digest as opaque owner evidence. + +This identity receipt is neither publication attestation nor World lifecycle, Game Session catalog, Entity placement, or gameplay-admission proof. The receiver remains disabled by default; its [implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-foundation) records wiring and proof limits. Enabling the handoff does not authorize canonical Draft writes or ACTIVE. + ## gRPC APIs - `GetRoom` – retrieves room data including exits and environmental effects through `RoomInstanceRef`. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 16945d1cfe..0d3ef8522c 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -20,6 +20,12 @@ Official-hosted creator-content acceptance remains an unimplemented target gap; The Game Design owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented with immutable request/digest/tenant-source evidence. The canonical behavior is owned by [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback). The bounded implementation and its focused proof are named in the [Capability Status](#capability-status) and [Validation and Proof](#validation-and-proof) entries below. These prove bounded storage and readback, not authenticated creator authorization, Account enrollment, runtime admission, or a playable environment. No creation RPC or activation is introduced, and broader capability ratings remain unchanged. +### Authored-world source foundation + +The bounded source prerequisite implements owner-local immutable registration/readback, exact same-namespace Game Session/World source reads, and an atomic fresh-source delivery claim with exact World acknowledgement storage. Its canonical contract is [authored-world source evidence and World delivery](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-source-evidence-and-world-delivery). Production anchors are `GameAuthoredWorldSourceRepository`, `GameAuthoredWorldSourceDeliveryRepository`, `TenantIdentityGrpcService`, V34.1, and V34.2. The target-native V34.2 delivery DDL preserves the prepared source migration's content without importing later publication migrations. + +The clean-baseline Common/Game Design/World full check and boot-jar gate passes. Game Design's 333 unit cases execute after fixture repair; the unchanged Common 199 and World 187 passing unit results are reused from the preceding gate. All 44 Game Design and 27 World integration cases are skipped locally without Docker, including source registration/delivery, World intake, retained-key guards, and physical peer proof. Integration compilation and static checks are not PostgreSQL or live deployment proof. No automatic delivery dispatcher or authenticated creator-facing source-registration ingress is included; those remain owner implementation obligations. Genuine release publication, World materialization/ACTIVE, Game Session catalog association, Entity placement, and final Account settlement remain separate open handoffs. + ### Script and plugin transition reconciliation Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index e6e42d9651..841ffe0671 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -10,6 +10,12 @@ This tracker is the permanent reader-facing implementation record for world runt The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. The focused unit-test anchors in the capability table cover service-local seams; PostgreSQL race/restart and live Compose proof remain unclaimed. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). +### Authored-world source foundation + +The bounded [World authored-source intake](../../architecture/microservices/world-management-service/api-contracts.md#authored-world-source-intake) implements an exact Game Design peer boundary, source verification before the owner transaction, persisted canonical tenant association and receipt, and authenticated exact retry/readback. V23.1 stores this association; V24 denies legacy numeric writes into canonical-associated/reserved tenant rows. The separate intake handler and file-backed mTLS client configuration remain default-off under `firemud.authored-world-source.enabled`; no deployment enablement or automatic Game Design dispatcher is included. + +The Common/Game Design/World full check, schema generation, integration compilation, static analysis, and boot-jar gate passes. World's 187 unit cases execute in the initial gate and are reused unchanged in the corrected gate. All 27 World integration cases are skipped without Docker; no physical PostgreSQL, retained-row migration, real peer, fresh-image boot, or end-to-end delivery proof is claimed. This receipt does not establish canonical Draft-write authorization, release attestation, materialization/ACTIVE, Game Session association, Entity placement, or the Account commit/abort settlement boundary. Those handoffs and their serving-authority, capacity/readiness, and lifecycle-fence proofs remain open. + ## Packet 4 Status and Proof Gaps - `GR-2.1` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) requires world runtime state to distinguish the durable playable-state namespace and `playableStateScope` from a disposable instance and to classify owner data before replacement. Current world instance and lifecycle evidence remains partial; no exhaustive S1/S2/S3 mapping or cleanup proof is claimed. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 13c74b1af5..2bf2585f16 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -7,6 +7,9 @@ option java_multiple_files = true; // Authenticated owner-local reads of persisted runtime and fresh-creation tenant evidence. service TenantIdentityService { + // Exact same-namespace Game Session/World read of immutable authored source evidence. + rpc ResolveAuthoredWorldSource(ResolveAuthoredWorldSourceRequest) + returns (ResolveAuthoredWorldSourceResponse); // Exact same-namespace Account/Game Session read of owner-created tenant evidence. rpc ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse); @@ -152,3 +155,27 @@ message ResolveFreshTenantCreationResponse { string provenance_kind = 9; string evidence_digest = 10; } + +message ResolveAuthoredWorldSourceRequest { + string request_id = 1; + string operation_id = 2; + string canonical_tenant_id = 3; + string world_slug = 4; +} + +message ResolveAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string registration_request_id = 4; + string operation_id = 5; + string request_digest = 6; + string canonical_tenant_id = 7; + string tenant_slug = 8; + string world_slug = 9; + string world_display_name = 10; + int64 source_game_row_id = 11; + string source_game_tenant_key = 12; + string provenance_kind = 13; + string evidence_digest = 14; +} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index d9c7fd624c..0d06d4087b 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -34,6 +34,68 @@ service WorldManagementService { rpc ApplyRoomAmbientStatePatch(ApplyRoomAmbientStatePatchRequest) returns (ApplyRoomAmbientStatePatchResponse); } +// Explicitly unwired authenticated authored-source intake boundary. This service remains separate +// from the runtime WorldManagementService until its caller and deployment path are authorized. +service WorldAuthoredSourceIntakeService { + rpc IntakeAuthoredWorldSource(IntakeAuthoredWorldSourceRequest) + returns (IntakeAuthoredWorldSourceResponse); + rpc ReadAuthoredWorldSourceIntake(ReadAuthoredWorldSourceIntakeRequest) + returns (ReadAuthoredWorldSourceIntakeResponse); +} + +message IntakeAuthoredWorldSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; +} + +message IntakeAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + string operation_id = 8; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 9; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 10; +} + +message ReadAuthoredWorldSourceIntakeRequest { + int32 schema_version = 1; + string target_namespace = 2; + // A distinct nonnil identity for this read; intake_request_id remains the stored receipt key. + string request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string expected_source_evidence_digest = 8; +} + +message ReadAuthoredWorldSourceIntakeResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string expected_source_evidence_digest = 8; + string operation_id = 9; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 10; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 11; +} + enum WorldInstanceLifecycleStatus { WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED = 0; WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING = 1; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java new file mode 100644 index 0000000000..a53c0b5511 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.util.concurrent.Executor; + +/** Authenticates the exact server workload before gRPC releases request headers or body. */ +public final class GrpcServerPeerIdentityCallCredentials extends CallCredentials { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + var sslSession = + requestInfo == null || requestInfo.getTransportAttrs() == null + ? null + : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + boolean exactPeer = + GrpcPeerIdentity.fromSslSession(sslSession) + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false); + if (!exactPeer) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Request requires the exact authenticated server workload identity")); + return; + } + applier.apply(new Metadata()); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java new file mode 100644 index 0000000000..aa43249ae9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.tenant; + +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.TenantIdentityServiceGrpc; + +/** Explicit mTLS client for exact, non-mutating Game Design authored-world source reads. */ +public final class AuthoredWorldSourceClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world source client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world source client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Reads the exact persisted source receipt without registering a World association. */ + public AuthoredWorldSourceEvidence read(AuthoredWorldSourceGrpcCodec.ReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveAuthoredWorldSource(AuthoredWorldSourceGrpcCodec.toReadRequest(request)); + try { + return AuthoredWorldSourceGrpcCodec.fromReadResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world source evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return TenantIdentityServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub requireStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world source client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Authored-world source request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Authored-world source reads require 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( + "Authored-world source reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Authored-world source reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Authored-world source " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Authored-world source " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java new file mode 100644 index 0000000000..a6a4a31297 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Canonical request and receipt digests for Game Design authored-world source evidence. */ +public final class AuthoredWorldSourceDigest { + private static final String REQUEST_DOMAIN = "game-design-authored-world-source-request/v1"; + private static final String RECEIPT_DOMAIN = "game-design-authored-world-source-receipt/v1"; + private static final Pattern CANONICAL_SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldSourceDigest() {} + + public static String requestDigest( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return GameTenantCreationDigest.digest( + REQUEST_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName); + } + + public static String evidenceDigest( + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + requireNonNil(operationId, "operationId"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + validateSourceGameTenantKey(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V29".equals(provenanceKind)) { + throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); + } + return GameTenantCreationDigest.digest( + RECEIPT_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + operationId.toString(), + requestDigest, + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind); + } + + public static void validateReadSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(worldSlug, "worldSlug"); + } + + private static void validateRequestTuple( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(registrationRequestId, "registrationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(tenantSlug, "tenantSlug"); + validateSlug(worldSlug, "worldSlug"); + validateDisplayName(worldDisplayName); + } + + private static void validateSlug(String value, String label) { + Objects.requireNonNull(value, label); + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + if (byteLength == 0 || byteLength > 120 || !CANONICAL_SLUG.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical routing selector"); + } + } + + private static void validateDisplayName(String value) { + Objects.requireNonNull(value, "worldDisplayName"); + if (value.isBlank() || value.length() > 200 || value.codePointCount(0, value.length()) > 100) { + throw new IllegalArgumentException( + "worldDisplayName must be nonblank and contain at most 100 Unicode code points"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void validateSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java new file mode 100644 index 0000000000..c09fb7a277 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidence.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** Closed immutable Game Design evidence for one registered authored-world selector source. */ +public record AuthoredWorldSourceEvidence( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + + public AuthoredWorldSourceEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world source schema version"); + } + Objects.requireNonNull(requestDigest, "requestDigest"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + String expectedRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + if (!expectedRequestDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the registration tuple"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + if (!GameTenantCreationDigest.isDigest(evidenceDigest)) { + throw new IllegalArgumentException("evidenceDigest must be a lowercase SHA-256 digest"); + } + String expectedEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + if (!expectedEvidenceDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Evidence digest does not match the immutable tuple"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java new file mode 100644 index 0000000000..a995782343 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; + +/** Closed request mapping and exact readback validation for authored-world source RPCs. */ +public final class AuthoredWorldSourceGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + /** Exact, non-mutating source read selector and caller-owned read identity. */ + public record ReadRequest( + String targetNamespace, + UUID requestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug) { + public ReadRequest { + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(requestId, "requestId"); + requireNonNil(operationId, "operationId"); + } + } + + private AuthoredWorldSourceGrpcCodec() {} + + /** Encodes exactly the owner read identity and source selector. */ + public static ResolveAuthoredWorldSourceRequest toReadRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setOperationId(request.operationId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .build(); + } + + /** Decodes the complete closed receipt and binds all echoed fields to the exact read request. */ + public static AuthoredWorldSourceEvidence fromReadResponse( + ReadRequest request, ResolveAuthoredWorldSourceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response); + + AuthoredWorldSourceEvidence evidence; + try { + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "requestId"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Authored-world source read request echo changed"); + } + evidence = + new AuthoredWorldSourceEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid( + response.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + response.getRequestDigest(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getTenantSlug(), + response.getWorldSlug(), + response.getWorldDisplayName(), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind(), + response.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world source response is invalid", exception); + } + + if (!request.targetNamespace().equals(evidence.targetNamespace()) + || !request.operationId().equals(evidence.operationId()) + || !request.canonicalTenantId().equals(evidence.canonicalTenantId()) + || !request.worldSlug().equals(evidence.worldSlug())) { + throw new IllegalArgumentException( + "Authored-world source response does not match the exact request"); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Authored-world source response contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + requireNonNil(parsed, label); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String label) { + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java new file mode 100644 index 0000000000..9bd4be4004 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.common.tenant; + +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.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; + +/** Explicit mTLS client for World's authenticated authored-source intake and exact readback. */ +public final class WorldAuthoredSourceIntakeClient + extends AbstractReloadingBlockingGrpcClient< + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldAuthoredSourceIntakeClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldAuthoredSourceIntakeClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World authored-source intake client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "World authored-source intake client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Sends one bounded intake request; transport failures are never retried blindly. */ + public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt intake( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .intakeAuthoredWorldSource(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake receipt", exception); + } + } + + /** Reads one exact committed World receipt with its separate caller-owned read identity. */ + public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt read( + WorldAuthoredSourceIntakeGrpcCodec.ReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.binding().targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredWorldSourceIntake( + WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake readback", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedWorldPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedWorldPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedWorldPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World authored-source intake client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "World authored-source intake request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World authored-source intake 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( + "World authored-source intake requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World authored-source intake requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "World authored-source intake " + label + " must be a readable file-backed path", + exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World authored-source intake " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java new file mode 100644 index 0000000000..577ccff3c1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java @@ -0,0 +1,307 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; + +/** Closed request mapping and exact echo validation for the World authored-source intake RPCs. */ +public final class WorldAuthoredSourceIntakeGrpcCodec { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DIGEST_DOMAIN = "world-authored-source-intake-request/v1"; + + /** Complete canonical binding accepted by intake and echoed by both World RPCs. */ + public record IntakeRequest( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + public IntakeRequest { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireDigest(expectedSourceEvidenceDigest, "expectedSourceEvidenceDigest"); + } + } + + /** A committed World receipt read using a distinct request identity and the full intake tuple. */ + public record ReadRequest(IntakeRequest binding, UUID requestId) { + public ReadRequest { + Objects.requireNonNull(binding, "binding"); + requireNonNil(requestId, "requestId"); + if (requestId.equals(binding.intakeRequestId())) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + } + } + + /** Public receipt fields. receiptDigest is opaque because it also binds World's private key. */ + public record CommittedReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest) { + public CommittedReceipt { + IntakeRequest binding = + new IntakeRequest( + schemaVersion, + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest); + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding).equals(requestDigest)) { + throw new IllegalArgumentException("World intake requestDigest does not match its binding"); + } + } + } + + private WorldAuthoredSourceIntakeGrpcCodec() {} + + /** Encodes exactly the validated original intake binding. */ + public static IntakeAuthoredWorldSourceRequest toIntakeRequest(IntakeRequest request) { + Objects.requireNonNull(request, "request"); + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .build(); + } + + /** Encodes the full intake binding and the caller-owned read request identity. */ + public static ReadAuthoredWorldSourceIntakeRequest toReadRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + IntakeRequest binding = request.binding(); + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(binding.schemaVersion()) + .setTargetNamespace(binding.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setIntakeRequestId(binding.intakeRequestId().toString()) + .setCanonicalTenantId(binding.canonicalTenantId().toString()) + .setWorldSlug(binding.worldSlug()) + .setSourceOperationId(binding.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(binding.expectedSourceEvidenceDigest()) + .build(); + } + + /** Decodes the complete closed intake request before any owner access. */ + public static IntakeRequest fromIntakeRequest(IntakeAuthoredWorldSourceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "IntakeAuthoredWorldSource request"); + return new IntakeRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest()); + } + + /** Decodes a closed exact-read request; requestId belongs only to the read itself. */ + public static ReadRequest fromReadRequest(ReadAuthoredWorldSourceIntakeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredWorldSourceIntake request"); + IntakeRequest binding = + new IntakeRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest()); + return new ReadRequest(binding, parseCanonicalNonNilUuid(request.getRequestId(), "requestId")); + } + + /** Encodes only a fully validated committed receipt and its exact original request binding. */ + public static IntakeAuthoredWorldSourceResponse toIntakeResponse( + IntakeRequest request, CommittedReceipt receipt) { + requireExactBinding(request, receipt); + return IntakeAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .build(); + } + + /** Encodes a fully validated committed receipt and echoes the distinct read identity. */ + public static ReadAuthoredWorldSourceIntakeResponse toReadResponse( + ReadRequest request, CommittedReceipt receipt) { + Objects.requireNonNull(request, "request"); + requireExactBinding(request.binding(), receipt); + return ReadAuthoredWorldSourceIntakeResponse.newBuilder() + .setSchemaVersion(request.binding().schemaVersion()) + .setTargetNamespace(request.binding().targetNamespace()) + .setRequestId(request.requestId().toString()) + .setIntakeRequestId(request.binding().intakeRequestId().toString()) + .setCanonicalTenantId(request.binding().canonicalTenantId().toString()) + .setWorldSlug(request.binding().worldSlug()) + .setSourceOperationId(request.binding().sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.binding().expectedSourceEvidenceDigest()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .build(); + } + + /** Validates all echoed request fields and the public, owner-authenticated receipt fields. */ + public static CommittedReceipt fromIntakeResponse( + IntakeRequest request, IntakeAuthoredWorldSourceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "IntakeAuthoredWorldSource response"); + IntakeRequest echoed = + new IntakeRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getWorldSlug(), + parseCanonicalNonNilUuid(response.getSourceOperationId(), "sourceOperationId"), + response.getExpectedSourceEvidenceDigest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("World intake response does not echo the exact request"); + } + return new CommittedReceipt( + echoed.schemaVersion(), + echoed.targetNamespace(), + echoed.intakeRequestId(), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + echoed.canonicalTenantId(), + echoed.worldSlug(), + echoed.sourceOperationId(), + echoed.expectedSourceEvidenceDigest(), + response.getRequestDigest(), + response.getReceiptDigest()); + } + + /** Validates the separate read identity, full original binding, and committed receipt. */ + public static CommittedReceipt fromReadResponse( + ReadRequest request, ReadAuthoredWorldSourceIntakeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredWorldSourceIntake response"); + IntakeRequest echoed = + new IntakeRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getWorldSlug(), + parseCanonicalNonNilUuid(response.getSourceOperationId(), "sourceOperationId"), + response.getExpectedSourceEvidenceDigest()); + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "requestId"); + if (!request.binding().equals(echoed) || !request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException( + "World intake read response does not echo the exact request"); + } + return new CommittedReceipt( + echoed.schemaVersion(), + echoed.targetNamespace(), + echoed.intakeRequestId(), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + echoed.canonicalTenantId(), + echoed.worldSlug(), + echoed.sourceOperationId(), + echoed.expectedSourceEvidenceDigest(), + response.getRequestDigest(), + response.getReceiptDigest()); + } + + /** Recomputable request digest defined by the World intake contract. */ + public static String requestDigest(IntakeRequest request) { + Objects.requireNonNull(request, "request"); + return GameTenantCreationDigest.digest( + REQUEST_DIGEST_DOMAIN, + request.targetNamespace(), + request.intakeRequestId().toString(), + request.canonicalTenantId().toString(), + request.worldSlug(), + request.sourceOperationId().toString(), + request.expectedSourceEvidenceDigest()); + } + + private static void requireExactBinding(IntakeRequest request, CommittedReceipt receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if (receipt.schemaVersion() != request.schemaVersion() + || !receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.intakeRequestId().equals(request.intakeRequestId()) + || !receipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !receipt.worldSlug().equals(request.worldSlug()) + || !receipt.sourceOperationId().equals(request.sourceOperationId()) + || !receipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest()) + || !receipt.requestDigest().equals(requestDigest(request))) { + throw new IllegalArgumentException( + "World committed receipt does not match the exact request"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + requireNonNil(parsed, label); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (!GameTenantCreationDigest.isDigest(value)) { + throw new IllegalArgumentException(label + " must be canonical SHA-256 text"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java new file mode 100644 index 0000000000..7328955cbd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldSourceClientTest { + private static final String NAMESPACE = "test"; + private static final AuthoredWorldSourceGrpcCodec.ReadRequest REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + "world-one"); + + @Test + void rejectsPlaintextMissingClasspathAndUnreadableTlsMaterialBeforeChannelCreation( + @TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing-client.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndRejectsNamespaceMismatch(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldSourceClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + "other", + REQUEST.requestId(), + REQUEST.operationId(), + REQUEST.canonicalTenantId(), + REQUEST.worldSlug()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesTheConfiguredGameDesignTargetOnlyOnExplicitInit(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + AuthoredWorldSourceClient client = + new AuthoredWorldSourceClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static AuthoredWorldSourceClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldSourceClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(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("server-ca.crt"), "CA certificate").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java new file mode 100644 index 0000000000..523aafbebe --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java @@ -0,0 +1,398 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceEvidenceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REGISTRATION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String TENANT_SLUG = "north-star"; + private static final String WORLD_SLUG = "violet-wilds"; + private static final String DISPLAY_NAME = "Café 🐉"; + private static final long SOURCE_GAME_ROW_ID = 42L; + private static final String SOURCE_GAME_TENANT_KEY = "legacy-game-tenant-42"; + private static final String PROVENANCE = "RETAINED_GAME_V29"; + + @Test + void acceptsClosedNewAndRetainedSourceEvidenceAndRecomputesBothDigests() { + assertThat(evidence("NEW_GAME_ROW").provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(evidence("RETAINED_GAME_V29").provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + } + + @Test + void acceptsMaximumSelectorBytesAndDisplayCodePoints() { + String maximumTenantSlug = "a".repeat(120); + String maximumWorldSlug = "b".repeat(120); + String maximumDisplayName = "é".repeat(100); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_ID, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + + assertThat( + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + maximumTenantSlug, + maximumWorldSlug, + maximumDisplayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE, + evidenceDigest) + .worldDisplayName()) + .hasSize(100); + } + + @Test + void rejectsUnsupportedVersionMalformedIdentitySelectorsAndDisplayName() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertInvalid( + 2, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + "bad.namespace", + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + new UUID(0L, 0L), + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + new UUID(0L, 0L), + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + new UUID(0L, 0L), + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "North-Star", + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + "a".repeat(121), + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + "bad_slug", + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + " ", + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "😀".repeat(101), + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + "bad" + (char) 0xd800, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertThat(valid.worldDisplayName()).isEqualTo(DISPLAY_NAME); + } + + @Test + void rejectsChangedRequestReceiptSourceBoundsAndUnknownProvenance() { + AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + "sha256:" + "0".repeat(64), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Request digest"); + assertThatThrownBy( + () -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + "sha256:" + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Evidence digest"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + 0L, + SOURCE_GAME_TENANT_KEY, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "x".repeat(37), + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + "bad" + (char) 0xd800, + PROVENANCE); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "OTHER"); + assertInvalid( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "RETAINED_GAME_V30"); + } + + private static AuthoredWorldSourceEvidence evidence(String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT_ID, TENANT_SLUG, WORLD_SLUG, DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + TENANT_SLUG, + WORLD_SLUG, + DISPLAY_NAME, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + provenanceKind, + evidenceDigest); + } + + private static void assertInvalid( + int schemaVersion, + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + assertThatThrownBy( + () -> { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind); + new AuthoredWorldSourceEvidence( + schemaVersion, + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + }) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java new file mode 100644 index 0000000000..07075347b5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static final UUID REQUEST_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final AuthoredWorldSourceGrpcCodec.ReadRequest REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, TENANT_ID, "world-one"); + + @Test + void encodesTheExactReadTupleAndDecodesTheCompleteReceipt() { + var encoded = AuthoredWorldSourceGrpcCodec.toReadRequest(REQUEST); + assertThat(encoded.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(encoded.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(encoded.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(encoded.getWorldSlug()).isEqualTo("world-one"); + assertThat(encoded.getUnknownFields().asMap()).isEmpty(); + + AuthoredWorldSourceEvidence evidence = + AuthoredWorldSourceGrpcCodec.fromReadResponse(REQUEST, response()); + assertThat(evidence.registrationRequestId()).isEqualTo(REGISTRATION_REQUEST_ID); + assertThat(evidence.operationId()).isEqualTo(OPERATION_ID); + assertThat(evidence.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(evidence.tenantSlug()).isEqualTo("tenant-one"); + assertThat(evidence.worldSlug()).isEqualTo("world-one"); + assertThat(evidence.worldDisplayName()).isEqualTo("Wörld"); + assertThat(evidence.sourceGameRowId()).isEqualTo(19L); + assertThat(evidence.sourceGameTenantKey()).isEqualTo("source-key"); + assertThat(evidence.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + } + + @Test + void rejectsMalformedReadSelectorsBeforeEncoding() { + for (Runnable invalid : + List.of( + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + "Other", REQUEST_ID, OPERATION_ID, TENANT_ID, "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, new UUID(0L, 0L), OPERATION_ID, TENANT_ID, "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, new UUID(0L, 0L), TENANT_ID, "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, new UUID(0L, 0L), "world-one"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, TENANT_ID, "World"), + () -> + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, REQUEST_ID, OPERATION_ID, TENANT_ID, "w".repeat(121)))) { + assertThatThrownBy(invalid::run).isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownFieldsAndEveryChangedReceiptField() { + ResolveAuthoredWorldSourceResponse valid = response(); + for (ResolveAuthoredWorldSourceResponse changed : + List.of( + valid.toBuilder().setSchemaVersion(2).build(), + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setRequestId(REGISTRATION_REQUEST_ID.toString()).build(), + valid.toBuilder().setRegistrationRequestId(REQUEST_ID.toString()).build(), + valid.toBuilder().setOperationId(REQUEST_ID.toString()).build(), + valid.toBuilder().setRequestDigest("sha256:" + "0".repeat(64)).build(), + valid.toBuilder().setCanonicalTenantId(REQUEST_ID.toString()).build(), + valid.toBuilder().setTenantSlug("tenant-other").build(), + valid.toBuilder().setWorldSlug("world-other").build(), + valid.toBuilder().setWorldDisplayName("World").build(), + valid.toBuilder().setSourceGameRowId(20L).build(), + valid.toBuilder().setSourceGameTenantKey("changed-key").build(), + valid.toBuilder().setProvenanceKind("RETAINED_GAME_V30").build(), + valid.toBuilder().setEvidenceDigest("sha256:" + "0".repeat(64)).build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadResponse(REQUEST, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsCoherentRepliesForAnotherNamespaceOperationTenantOrWorld() { + for (ResolveAuthoredWorldSourceResponse changed : + List.of( + response("other", TENANT_ID, OPERATION_ID, "world-one"), + response(NAMESPACE, TENANT_ID, REQUEST_ID, "world-one"), + response(NAMESPACE, REQUEST_ID, OPERATION_ID, "world-one"), + response(NAMESPACE, TENANT_ID, OPERATION_ID, "other-world"))) { + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadResponse(REQUEST, changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact request"); + } + } + + private static ResolveAuthoredWorldSourceResponse response() { + return response(NAMESPACE, TENANT_ID, OPERATION_ID, "world-one"); + } + + private static ResolveAuthoredWorldSourceResponse response( + String namespace, UUID tenantId, UUID operationId, String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, REGISTRATION_REQUEST_ID, tenantId, "tenant-one", worldSlug, "Wörld"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + REGISTRATION_REQUEST_ID, + operationId, + requestDigest, + tenantId, + "tenant-one", + worldSlug, + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW"); + return ResolveAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setRequestId(REQUEST_ID.toString()) + .setRegistrationRequestId(REGISTRATION_REQUEST_ID.toString()) + .setOperationId(operationId.toString()) + .setRequestDigest(requestDigest) + .setCanonicalTenantId(tenantId.toString()) + .setTenantSlug("tenant-one") + .setWorldSlug(worldSlug) + .setWorldDisplayName("Wörld") + .setSourceGameRowId(19L) + .setSourceGameTenantKey("source-key") + .setProvenanceKind("NEW_GAME_ROW") + .setEvidenceDigest(evidenceDigest) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java new file mode 100644 index 0000000000..a30c142c85 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldAuthoredSourceIntakeClientTest { + private static final String NAMESPACE = "test"; + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String RECEIPT_DIGEST = "sha256:" + "b".repeat(64); + private static final WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest INTAKE_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "world-one", + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + SOURCE_DIGEST); + private static final WorldAuthoredSourceIntakeGrpcCodec.ReadRequest READ_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest( + INTAKE_REQUEST, UUID.fromString("42345678-1234-4234-8234-123456789abc")); + + @Test + void rejectsPlaintextClasspathAndUnreadableTlsMaterialBeforeChannelCreation(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(dir); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(dir.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(dir.resolve("missing-client.key").toString()); + missingFiles.setCaCert(dir.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitLifecycleAndExactConfiguredNamespace(@TempDir Path dir) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + WorldAuthoredSourceIntakeClient client = newClient(fileBackedMtls(dir), channelFactory); + try { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.intake( + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + "other", + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + INTAKE_REQUEST.expectedSourceEvidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesConfiguredWorldTargetOnceAndCannotRestartAfterClose(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:7676"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("world.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient(endpoints, tls, channelFactory, NAMESPACE); + + client.init(); + client.init(); + client.close(); + + verify(channelFactory) + .buildChannel( + eq("world.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("is closed"); + } + + @Test + void sendsOneIntakeAndReturnsOnlyAValidatedExactWorldReceipt(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + IntakeAuthoredWorldSourceResponse response = intakeResponse(INTAKE_REQUEST); + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn(response); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt = client.intake(INTAKE_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(INTAKE_REQUEST.intakeRequestId()); + assertThat(receipt.operationId()) + .isEqualTo(UUID.fromString("52345678-1234-4234-8234-123456789abc")); + assertThat(receipt.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST)); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST) + .getDescriptorForType() + .getFields()) + .extracting(field -> field.getName()) + .doesNotContain("world_tenant_key", "local_tenant_key", "tenant_id"); + } + + @Test + void rejectsChangedEchoesAndUnknownResponseFields(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn(intakeResponse(INTAKE_REQUEST).toBuilder().setWorldSlug("other-world").build()); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn( + intakeResponse(INTAKE_REQUEST).toBuilder().setUnknownFields(unknownField()).build()); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + + ReadAuthoredWorldSourceIntakeResponse alteredRead = + readResponse(READ_REQUEST).toBuilder() + .setRequestId(INTAKE_REQUEST.intakeRequestId().toString()) + .build(); + when(stub.readAuthoredWorldSourceIntake(any(ReadAuthoredWorldSourceIntakeRequest.class))) + .thenReturn(alteredRead); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake readback"); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(StatusRuntimeException.class); + verify(stub, org.mockito.Mockito.times(3)) + .intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class)); + } + + @Test + void readRequiresAndReturnsTheSeparateExactReadIdentity(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.readAuthoredWorldSourceIntake(any(ReadAuthoredWorldSourceIntakeRequest.class))) + .thenReturn(readResponse(READ_REQUEST)); + + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt = client.read(READ_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(INTAKE_REQUEST.intakeRequestId()); + assertThat(receipt.sourceOperationId()).isEqualTo(INTAKE_REQUEST.sourceOperationId()); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .readAuthoredWorldSourceIntake( + WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(READ_REQUEST)); + } + + private static WorldAuthoredSourceIntakeClient clientWithStub( + Path directory, + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub) + throws Exception { + WorldAuthoredSourceIntakeClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + setField(AbstractReloadingBlockingGrpcClient.class, client, "stub", stub); + setField(WorldAuthoredSourceIntakeClient.class, client, "initialized", true); + return client; + } + + private static IntakeAuthoredWorldSourceResponse intakeResponse( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(request, receipt(request)); + } + + private static ReadAuthoredWorldSourceIntakeResponse readResponse( + WorldAuthoredSourceIntakeGrpcCodec.ReadRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(request, receipt(request.binding())); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + return new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + UUID.fromString("52345678-1234-4234-8234-123456789abc"), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + RECEIPT_DIGEST); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static void setField(Class declaringClass, Object target, String name, Object value) + throws Exception { + Field field = declaringClass.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + + private static WorldAuthoredSourceIntakeClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new WorldAuthoredSourceIntakeClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(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("server-ca.crt"), "CA certificate").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java new file mode 100644 index 0000000000..80fb74bda4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeGrpcCodecTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = digest('a'); + private static final String REQUEST_DIGEST = + "sha256:d8b4609586debeae9752cc22ddb58a686fa770ea5928a52aefab71494164e1ce"; + private static final String RECEIPT_DIGEST = digest('b'); + private static final IntakeRequest BINDING = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + + @Test + void decodesAndEchoesTheFullIntakeBindingAndPublicReceipt() { + var request = intakeRequest(); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request)).isEqualTo(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING)).isEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(BINDING).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(BINDING)).isEqualTo(REQUEST_DIGEST); + IntakeAuthoredWorldSourceResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, receipt); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(response.getExpectedSourceEvidenceDigest()).isEqualTo(SOURCE_DIGEST); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(response.getReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, response)) + .isEqualTo(receipt); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + } + + @Test + void exactReadUsesAndEchoesItsSeparateRequestIdentity() { + ReadAuthoredWorldSourceIntakeRequest request = readRequest(); + ReadRequest decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + assertThat(decoded.binding()).isEqualTo(BINDING); + assertThat(decoded.requestId()).isEqualTo(READ_REQUEST_ID); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded)).isEqualTo(request); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(decoded).getUnknownFields().asMap()) + .isEmpty(); + + CommittedReceipt receipt = committedReceipt(BINDING); + ReadAuthoredWorldSourceIntakeResponse response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(decoded, receipt); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + assertThat(response.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(response.getWorldSlug()).isEqualTo(WORLD_SLUG); + assertThat(response.getSourceOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(decoded, response)) + .isEqualTo(receipt); + } + + @Test + void rejectsMalformedClosedIntakeRequests() { + for (IntakeAuthoredWorldSourceRequest invalid : + List.of( + intakeRequest().toBuilder().setSchemaVersion(2).build(), + intakeRequest().toBuilder().setTargetNamespace("FireMUD").build(), + intakeRequest().toBuilder().setIntakeRequestId("not-a-uuid").build(), + intakeRequest().toBuilder().setCanonicalTenantId(new UUID(0L, 0L).toString()).build(), + intakeRequest().toBuilder().setWorldSlug("Violet-Wilds").build(), + intakeRequest().toBuilder().setWorldSlug("w".repeat(121)).build(), + intakeRequest().toBuilder() + .setSourceOperationId("00000000-0000-0000-0000-000000000000") + .build(), + intakeRequest().toBuilder().setExpectedSourceEvidenceDigest("sha256:BAD").build(), + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsReadRequestsThatReuseTheIntakeIdentityOrContainUnknownFields() { + for (ReadAuthoredWorldSourceIntakeRequest invalid : + List.of( + readRequest().toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build(), + readRequest().toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + readRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { + IntakeAuthoredWorldSourceResponse valid = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, committedReceipt(BINDING)); + for (IntakeAuthoredWorldSourceResponse invalid : + List.of( + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setIntakeRequestId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setCanonicalTenantId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setWorldSlug("other-world").build(), + valid.toBuilder().setSourceOperationId(READ_REQUEST_ID.toString()).build(), + valid.toBuilder().setExpectedSourceEvidenceDigest(digest('c')).build(), + valid.toBuilder().setOperationId("not-a-uuid").build(), + valid.toBuilder().setRequestDigest(digest('c')).build(), + valid.toBuilder().setReceiptDigest("sha256:invalid").build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(BINDING, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); + ReadAuthoredWorldSourceIntakeResponse readResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesToEncodeAReceiptForAnotherBinding() { + CommittedReceipt changed = + new CommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + OPERATION_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + "other-world", + SOURCE_OPERATION_ID, + SOURCE_DIGEST)), + RECEIPT_DIGEST); + assertThatThrownBy(() -> WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(BINDING, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setRequestId(READ_REQUEST_ID.toString()) + .setIntakeRequestId(INTAKE_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setSourceOperationId(SOURCE_OPERATION_ID.toString()) + .setExpectedSourceEvidenceDigest(SOURCE_DIGEST) + .build(); + } + + private static CommittedReceipt committedReceipt(IntakeRequest binding) { + return new CommittedReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 264cc3ebfc..a46e274d7e 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -12,6 +12,9 @@ firemudJooq { } dependencies { + testImplementation(libs.bouncycastle.pkix) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java new file mode 100644 index 0000000000..038acbf4bc --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java @@ -0,0 +1,604 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Durable Game Design outbox for exact, fresh authored-world source delivery to World. */ +@Repository +public class GameAuthoredWorldSourceDeliveryRepository { + private static final int SCHEMA_VERSION = 1; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + private static final int MAX_PENDING_BATCH_SIZE = 100; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table DELIVERY = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final Field DELIVERY_SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field DELIVERY_SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field DELIVERY_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field DELIVERY_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field DELIVERY_SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field DELIVERY_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field DELIVERY_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field DELIVERY_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field DELIVERY_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field DELIVERY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field DELIVERY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field DELIVERY_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field DELIVERY_SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field DELIVERY_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("intake_schema_version"), Integer.class); + private static final Field DELIVERY_INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field DELIVERY_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + private static final Field DELIVERY_WORLD_REQUEST_DIGEST = + DSL.field(DSL.name("world_request_digest"), String.class); + private static final Field DELIVERY_WORLD_RECEIPT_DIGEST = + DSL.field(DSL.name("world_receipt_digest"), String.class); + private static final Field DELIVERY_ACKNOWLEDGED_AT = + DSL.field(DSL.name("acknowledged_at"), OffsetDateTime.class); + + private static final Table SOURCE = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field SOURCE_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field SOURCE_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field GAME_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final Table TENANT_BINDING = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Field BINDING_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field BINDING_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field BINDING_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field BINDING_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected DSLContext is the repository's owner transaction collaborator.") + public GameAuthoredWorldSourceDeliveryRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Persists one stable World intake identity inside the source-registration transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim enqueueFresh(AuthoredWorldSourceEvidence source) { + requireActiveWritableOwnerTransaction(); + requireFreshSource(source); + requireExactPersistedSource(source); + + Record existing = findDelivery(source.operationId()); + if (existing != null) { + DeliveryClaim claim = toClaim(existing); + requireSameSource(source, claim.source()); + return claim; + } + + UUID intakeRequestId = UUID.randomUUID(); + while (NIL_UUID.equals(intakeRequestId) || source.operationId().equals(intakeRequestId)) { + intakeRequestId = UUID.randomUUID(); + } + IntakeRequest request = + new IntakeRequest( + SCHEMA_VERSION, + source.targetNamespace(), + intakeRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + String intakeRequestDigest = WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request); + + int inserted = + dsl.insertInto(DELIVERY) + .set(DELIVERY_SOURCE_OPERATION_ID, source.operationId()) + .set(DELIVERY_SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(DELIVERY_NAMESPACE, source.targetNamespace()) + .set(DELIVERY_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(DELIVERY_SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(DELIVERY_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(DELIVERY_TENANT_SLUG, source.tenantSlug()) + .set(DELIVERY_WORLD_SLUG, source.worldSlug()) + .set(DELIVERY_WORLD_DISPLAY_NAME, source.worldDisplayName()) + .set(DELIVERY_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(DELIVERY_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(DELIVERY_PROVENANCE_KIND, source.provenanceKind()) + .set(DELIVERY_SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .set(DELIVERY_INTAKE_SCHEMA_VERSION, request.schemaVersion()) + .set(DELIVERY_INTAKE_REQUEST_ID, request.intakeRequestId()) + .set(DELIVERY_INTAKE_REQUEST_DIGEST, intakeRequestDigest) + .onConflictDoNothing() + .execute(); + if (inserted != 1) { + Record conflict = findDelivery(source.operationId()); + if (conflict != null) { + DeliveryClaim claim = toClaim(conflict); + requireSameSource(source, claim.source()); + return claim; + } + throw new DeliveryConflictException( + "Authored-world source delivery conflicts with an existing owner claim"); + } + + Record persisted = findDelivery(source.operationId()); + if (persisted == null) { + throw new IllegalStateException("Authored-world source delivery claim is missing"); + } + DeliveryClaim claim = toClaim(persisted); + requireSameSource(source, claim.source()); + if (!request.equals(claim.request()) || claim.acknowledgedReceipt().isPresent()) { + throw new DeliveryConflictException( + "Committed authored-world source delivery differs from its original claim"); + } + return claim; + } + + /** Reads one complete committed delivery claim without allocating or repairing it. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read(UUID sourceOperationId) { + requireNonNil(sourceOperationId, "sourceOperationId"); + requireCommittedOutcomeRead(); + Record record = findDelivery(sourceOperationId); + if (record == null) { + return Optional.empty(); + } + DeliveryClaim claim = toClaim(record); + requireExactPersistedSource(claim.source()); + return Optional.of(claim); + } + + /** + * Reads one bounded page of exact pending claims for this workload namespace. The stable intake + * request identity is the keyset cursor; callers cycle back to the beginning after reaching the + * end so a failed older claim cannot starve later claims. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public List readPending( + String targetNamespace, UUID afterIntakeRequestId, int limit) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + if (afterIntakeRequestId != null) { + requireNonNil(afterIntakeRequestId, "afterIntakeRequestId"); + } + if (limit < 1 || limit > MAX_PENDING_BATCH_SIZE) { + throw new IllegalArgumentException( + "Pending authored-world delivery page size must be between 1 and " + + MAX_PENDING_BATCH_SIZE); + } + requireCommittedOutcomeRead(); + + var rows = + dsl.selectFrom(DELIVERY) + .where( + DELIVERY_NAMESPACE + .eq(targetNamespace) + .and(DELIVERY_PROVENANCE_KIND.eq(NEW_GAME_ROW)) + .and(DELIVERY_WORLD_OPERATION_ID.isNull()) + .and(DELIVERY_WORLD_REQUEST_DIGEST.isNull()) + .and(DELIVERY_WORLD_RECEIPT_DIGEST.isNull()) + .and(DELIVERY_ACKNOWLEDGED_AT.isNull()) + .and( + afterIntakeRequestId == null + ? DSL.noCondition() + : DELIVERY_INTAKE_REQUEST_ID.gt(afterIntakeRequestId))) + .orderBy(DELIVERY_INTAKE_REQUEST_ID.asc()) + .limit(limit) + .fetch(); + List claims = new ArrayList<>(rows.size()); + for (Record row : rows) { + DeliveryClaim claim = toClaim(row); + if (!targetNamespace.equals(claim.request().targetNamespace()) + || claim.acknowledgedReceipt().isPresent()) { + throw new DeliveryConflictException( + "Pending authored-world delivery read returned a claim outside its exact selector"); + } + requireExactPersistedSource(claim.source()); + claims.add(claim); + } + return List.copyOf(claims); + } + + /** Records only the first full World receipt, or returns an identical concurrent winner. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim acknowledge(DeliveryClaim expected, CommittedReceipt receipt) { + requireActiveWritableOwnerTransaction(); + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(receipt, "receipt"); + requireFreshSource(expected.source()); + requireReceiptMatchesRequest(expected.request(), receipt); + + Record currentRecord = findDelivery(expected.source().operationId()); + if (currentRecord == null) { + throw new DeliveryConflictException("Authored-world source delivery claim is missing"); + } + DeliveryClaim current = toClaim(currentRecord); + requireSameClaim(expected, current); + requireExactPersistedSource(current.source()); + if (current.acknowledgedReceipt().isPresent()) { + CommittedReceipt original = current.acknowledgedReceipt().orElseThrow(); + if (!original.equals(receipt)) { + throw new DeliveryConflictException( + "Authored-world source delivery already has a different World receipt"); + } + return current; + } + + int updated = + dsl.update(DELIVERY) + .set(DELIVERY_WORLD_OPERATION_ID, receipt.operationId()) + .set(DELIVERY_WORLD_REQUEST_DIGEST, receipt.requestDigest()) + .set(DELIVERY_WORLD_RECEIPT_DIGEST, receipt.receiptDigest()) + .set(DELIVERY_ACKNOWLEDGED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where( + DELIVERY_SOURCE_OPERATION_ID + .eq(expected.source().operationId()) + .and(DELIVERY_WORLD_OPERATION_ID.isNull()) + .and(DELIVERY_WORLD_REQUEST_DIGEST.isNull()) + .and(DELIVERY_WORLD_RECEIPT_DIGEST.isNull()) + .and(DELIVERY_ACKNOWLEDGED_AT.isNull())) + .execute(); + if (updated > 1) { + throw new IllegalStateException("Authored-world source delivery ACK changed multiple rows"); + } + + Record acknowledgedRecord = findDelivery(expected.source().operationId()); + if (acknowledgedRecord == null) { + throw new IllegalStateException("Authored-world source delivery disappeared during ACK"); + } + DeliveryClaim acknowledged = toClaim(acknowledgedRecord); + requireSameClaim(expected, acknowledged); + CommittedReceipt durableReceipt = + acknowledged + .acknowledgedReceipt() + .orElseThrow( + () -> new DeliveryConflictException("World receipt ACK did not read back")); + if (!durableReceipt.equals(receipt)) { + throw new DeliveryConflictException( + "Concurrent authored-world source delivery ACK has a different World receipt"); + } + return acknowledged; + } + + /** Validates a pre-V41 registration retry when its optional delivery row already exists. */ + @Transactional(propagation = Propagation.MANDATORY) + void validateExistingIfPresent(AuthoredWorldSourceEvidence source) { + requireActiveWritableOwnerTransaction(); + requireFreshSource(source); + Record existing = findDelivery(source.operationId()); + if (existing == null) { + return; + } + DeliveryClaim claim = toClaim(existing); + requireSameSource(source, claim.source()); + } + + private Record findDelivery(UUID sourceOperationId) { + return dsl.selectFrom(DELIVERY) + .where(DELIVERY_SOURCE_OPERATION_ID.eq(sourceOperationId)) + .fetchOne(); + } + + private DeliveryClaim toClaim(Record row) { + AuthoredWorldSourceEvidence source; + IntakeRequest request; + Optional acknowledgedReceipt; + try { + source = + new AuthoredWorldSourceEvidence( + row.get(DELIVERY_SOURCE_SCHEMA_VERSION), + row.get(DELIVERY_NAMESPACE), + row.get(DELIVERY_REGISTRATION_REQUEST_ID), + row.get(DELIVERY_SOURCE_OPERATION_ID), + row.get(DELIVERY_SOURCE_REQUEST_DIGEST), + row.get(DELIVERY_CANONICAL_TENANT_ID), + row.get(DELIVERY_TENANT_SLUG), + row.get(DELIVERY_WORLD_SLUG), + row.get(DELIVERY_WORLD_DISPLAY_NAME), + row.get(DELIVERY_SOURCE_GAME_ROW_ID), + row.get(DELIVERY_SOURCE_GAME_TENANT_KEY), + row.get(DELIVERY_PROVENANCE_KIND), + row.get(DELIVERY_SOURCE_EVIDENCE_DIGEST)); + request = + new IntakeRequest( + row.get(DELIVERY_INTAKE_SCHEMA_VERSION), + row.get(DELIVERY_NAMESPACE), + row.get(DELIVERY_INTAKE_REQUEST_ID), + row.get(DELIVERY_CANONICAL_TENANT_ID), + row.get(DELIVERY_WORLD_SLUG), + row.get(DELIVERY_SOURCE_OPERATION_ID), + row.get(DELIVERY_SOURCE_EVIDENCE_DIGEST)); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request) + .equals(row.get(DELIVERY_INTAKE_REQUEST_DIGEST))) { + throw new IllegalArgumentException("Persisted World intake request digest is invalid"); + } + UUID worldOperationId = row.get(DELIVERY_WORLD_OPERATION_ID); + String worldRequestDigest = row.get(DELIVERY_WORLD_REQUEST_DIGEST); + String worldReceiptDigest = row.get(DELIVERY_WORLD_RECEIPT_DIGEST); + if (worldOperationId == null && worldRequestDigest == null && worldReceiptDigest == null) { + acknowledgedReceipt = Optional.empty(); + } else { + acknowledgedReceipt = + Optional.of( + new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + worldRequestDigest, + worldReceiptDigest)); + } + return new DeliveryClaim(source, request, acknowledgedReceipt); + } catch (RuntimeException exception) { + if (exception instanceof DeliveryConflictException conflict) { + throw conflict; + } + throw new InvalidDeliveryClaimException( + "Persisted authored-world source delivery claim is invalid", exception); + } + } + + private void requireExactPersistedSource(AuthoredWorldSourceEvidence expected) { + Record sourceRow = + dsl.selectFrom(SOURCE).where(SOURCE_OPERATION_ID.eq(expected.operationId())).fetchOne(); + if (sourceRow == null || !expected.equals(toSourceEvidence(sourceRow))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery does not match the complete persisted source receipt"); + } + + Record gameRow = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_ID.eq(expected.sourceGameRowId())) + .fetchOne(); + if (gameRow == null + || !Long.valueOf(expected.sourceGameRowId()).equals(gameRow.get(GAME_ID)) + || !expected.sourceGameTenantKey().equals(gameRow.get(GAME_TENANT_ID)) + || !expected.canonicalTenantId().equals(gameRow.get(GAME_CANONICAL_TENANT_ID)) + || !expected.provenanceKind().equals(gameRow.get(GAME_PROVENANCE_KIND)) + || !Long.valueOf(expected.sourceGameRowId()).equals(gameRow.get(GAME_SOURCE_ROW_ID)) + || !expected.sourceGameTenantKey().equals(gameRow.get(GAME_SOURCE_TENANT_KEY))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery source no longer matches its Game Design game row"); + } + + Record bindingRow = + dsl.select( + BINDING_NAMESPACE, + BINDING_CANONICAL_TENANT_ID, + BINDING_TENANT_SLUG, + BINDING_SOURCE_GAME_ROW_ID, + BINDING_SOURCE_GAME_TENANT_KEY, + BINDING_PROVENANCE_KIND) + .from(TENANT_BINDING) + .where( + BINDING_NAMESPACE + .eq(expected.targetNamespace()) + .and(BINDING_CANONICAL_TENANT_ID.eq(expected.canonicalTenantId()))) + .fetchOne(); + if (bindingRow == null + || !expected.tenantSlug().equals(bindingRow.get(BINDING_TENANT_SLUG)) + || !Long.valueOf(expected.sourceGameRowId()) + .equals(bindingRow.get(BINDING_SOURCE_GAME_ROW_ID)) + || !expected.sourceGameTenantKey().equals(bindingRow.get(BINDING_SOURCE_GAME_TENANT_KEY)) + || !expected.provenanceKind().equals(bindingRow.get(BINDING_PROVENANCE_KIND))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery source no longer matches its tenant selector binding"); + } + } + + private AuthoredWorldSourceEvidence toSourceEvidence(Record row) { + try { + return new AuthoredWorldSourceEvidence( + row.get(SOURCE_SCHEMA_VERSION), + row.get(SOURCE_NAMESPACE), + row.get(SOURCE_REGISTRATION_REQUEST_ID), + row.get(SOURCE_OPERATION_ID), + row.get(SOURCE_REQUEST_DIGEST), + row.get(SOURCE_CANONICAL_TENANT_ID), + row.get(SOURCE_TENANT_SLUG), + row.get(SOURCE_WORLD_SLUG), + row.get(SOURCE_WORLD_DISPLAY_NAME), + row.get(SOURCE_GAME_ROW_ID), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(SOURCE_PROVENANCE_KIND), + row.get(SOURCE_EVIDENCE_DIGEST)); + } catch (RuntimeException exception) { + throw new InvalidDeliveryClaimException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private static void requireSameClaim(DeliveryClaim expected, DeliveryClaim actual) { + requireSameSource(expected.source(), actual.source()); + if (!expected.request().equals(actual.request())) { + throw new DeliveryConflictException( + "Authored-world source delivery request identity changed after dispatch"); + } + } + + private static void requireSameSource( + AuthoredWorldSourceEvidence expected, AuthoredWorldSourceEvidence actual) { + if (!expected.equals(actual)) { + throw new DeliveryConflictException( + "Authored-world source delivery no longer matches its immutable source evidence"); + } + } + + private static void requireReceiptMatchesRequest( + IntakeRequest request, CommittedReceipt receipt) { + if (receipt.schemaVersion() != request.schemaVersion() + || !receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.intakeRequestId().equals(request.intakeRequestId()) + || !receipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !receipt.worldSlug().equals(request.worldSlug()) + || !receipt.sourceOperationId().equals(request.sourceOperationId()) + || !receipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest())) { + throw new DeliveryConflictException( + "World receipt does not bind the exact persisted authored-world source request"); + } + } + + private static void requireFreshSource(AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(source, "source"); + if (!NEW_GAME_ROW.equals(source.provenanceKind())) { + throw new DeliveryConflictException( + "Only a proven NEW_GAME_ROW authored-world source may be delivered to World"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireActiveWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Authored-world source delivery mutation requires an active writable owner transaction"); + } + } + + private static void requireCommittedOutcomeRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source delivery read requires a committed-outcome owner read"); + } + } + + /** Exact persisted source, immutable World intake identity, and first optional World ACK. */ + public record DeliveryClaim( + AuthoredWorldSourceEvidence source, + IntakeRequest request, + Optional acknowledgedReceipt) { + public DeliveryClaim { + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(acknowledgedReceipt, "acknowledgedReceipt"); + requireFreshSource(source); + IntakeRequest expected = + new IntakeRequest( + SCHEMA_VERSION, + source.targetNamespace(), + request.intakeRequestId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + if (!expected.equals(request)) { + throw new DeliveryConflictException( + "World intake request does not bind the complete authored-world source"); + } + acknowledgedReceipt.ifPresent(receipt -> requireReceiptMatchesRequest(request, receipt)); + } + } + + public static class DeliveryConflictException extends IllegalStateException { + public DeliveryConflictException(String message) { + super(message); + } + } + + public static final class InvalidDeliveryClaimException extends DeliveryConflictException { + public InvalidDeliveryClaimException(String message) { + super(message); + } + + public InvalidDeliveryClaimException(String message, Throwable cause) { + super(message); + initCause(cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java new file mode 100644 index 0000000000..0ba9f51fb5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java @@ -0,0 +1,469 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local immutable selector-source registration and exact committed readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class GameAuthoredWorldSourceRepository { + private static final int SCHEMA_VERSION = 1; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + private static final String RETAINED_GAME_V29 = "RETAINED_GAME_V29"; + + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field GAME_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final Table TENANT_SLUG_BINDING = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Field BINDING_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field BINDING_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field BINDING_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field BINDING_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + + private static final Table OPERATION = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field OPERATION_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field OPERATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + + private final DSLContext dsl; + private final GameAuthoredWorldSourceDeliveryRepository deliveryRepository; + + @Autowired + public GameAuthoredWorldSourceRepository( + DSLContext dsl, GameAuthoredWorldSourceDeliveryRepository deliveryRepository) { + this.dsl = dsl; + this.deliveryRepository = deliveryRepository; + } + + /** Retains the direct owner-test construction path while sharing its owner DSL context. */ + public GameAuthoredWorldSourceRepository(DSLContext dsl) { + this(dsl, new GameAuthoredWorldSourceDeliveryRepository(dsl)); + } + + /** + * Binds explicit authored-world selectors to one exact persisted Game Design tenant source. + * + *

The caller must own the encompassing Game Design transaction. The actual source game row is + * locked before request replay checks and selector claims, serializing registrations for one + * tenant without treating a template, display name, or legacy key as a selector. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + requireActiveOwnerTransaction(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + + GameSource source = lockGameSource(canonicalTenantId); + if (source == null) { + throw new RegistrationConflictException("Canonical tenant source game row is missing"); + } + requireConsistentGameSource(source); + + Record existingRequest = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (existingRequest != null) { + AuthoredWorldSourceEvidence receipt = toEvidence(existingRequest); + if (!requestDigest.equals(receipt.requestDigest()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !tenantSlug.equals(receipt.tenantSlug()) + || !worldSlug.equals(receipt.worldSlug()) + || !worldDisplayName.equals(receipt.worldDisplayName())) { + throw new RegistrationConflictException( + "Authored-world registration identity was reused with changed input"); + } + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + if (NEW_GAME_ROW.equals(receipt.provenanceKind())) { + // A missing pre-V41 delivery claim stays missing; exact source retry does not backfill it. + deliveryRepository.validateExistingIfPresent(receipt); + } + return receipt; + } + + ensureTenantSlugBinding(targetNamespace, tenantSlug, source); + UUID operationId = UUID.randomUUID(); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + operationId, + requestDigest, + source.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + + int inserted = + dsl.insertInto(OPERATION) + .set(OPERATION_ID, operationId) + .set(OPERATION_SCHEMA_VERSION, SCHEMA_VERSION) + .set(OPERATION_NAMESPACE, targetNamespace) + .set(REGISTRATION_REQUEST_ID, registrationRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(TENANT_SLUG, tenantSlug) + .set(WORLD_SLUG, worldSlug) + .set(WORLD_DISPLAY_NAME, worldDisplayName) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(PROVENANCE_KIND, source.provenanceKind()) + .set(EVIDENCE_DIGEST, evidenceDigest) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record requestConflict = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (requestConflict != null) { + throw new RegistrationConflictException( + "Authored-world registration identity was reused with changed input"); + } + Record selectorConflict = findByWorldSelector(targetNamespace, canonicalTenantId, worldSlug); + if (selectorConflict != null) { + throw new RegistrationConflictException( + "Authored-world selector is already owned by another source operation"); + } + throw new RegistrationConflictException( + "Authored-world source operation conflicts with an existing owner claim"); + } + + Record persisted = findByRegistrationRequest(targetNamespace, registrationRequestId); + if (persisted == null) { + throw new IllegalStateException("Committed authored-world source operation is missing"); + } + AuthoredWorldSourceEvidence receipt = toEvidence(persisted); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + if (NEW_GAME_ROW.equals(receipt.provenanceKind())) { + deliveryRepository.enqueueFresh(receipt); + } + return receipt; + } + + /** Reads one exact committed source operation without allocating or repairing selector state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID operationId, UUID canonicalTenantId, String worldSlug, String targetNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (operationId == null || operationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("operationId must be a canonical non-nil UUID"); + } + Record record = + dsl.selectFrom(OPERATION) + .where( + OPERATION_ID + .eq(operationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(OPERATION_NAMESPACE.eq(targetNamespace))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(record); + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source row is missing"); + } + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + return Optional.of(receipt); + } + + private void ensureTenantSlugBinding( + String targetNamespace, String tenantSlug, GameSource source) { + Record existing = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(targetNamespace) + .and(BINDING_CANONICAL_TENANT_ID.eq(source.canonicalTenantId()))) + .fetchOne(); + if (existing != null) { + requireMatchingBinding(existing, targetNamespace, tenantSlug, source); + return; + } + + int inserted = + dsl.insertInto(TENANT_SLUG_BINDING) + .set(BINDING_NAMESPACE, targetNamespace) + .set(BINDING_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(BINDING_TENANT_SLUG, tenantSlug) + .set(BINDING_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(BINDING_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(BINDING_PROVENANCE_KIND, source.provenanceKind()) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + return; + } + + Record tenantBinding = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(targetNamespace) + .and(BINDING_CANONICAL_TENANT_ID.eq(source.canonicalTenantId()))) + .fetchOne(); + if (tenantBinding != null) { + requireMatchingBinding(tenantBinding, targetNamespace, tenantSlug, source); + return; + } + Record slugOwner = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where(BINDING_NAMESPACE.eq(targetNamespace).and(BINDING_TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + if (slugOwner != null) { + throw new RegistrationConflictException( + "Tenant selector is already owned by another canonical tenant"); + } + throw new RegistrationConflictException( + "Tenant selector binding conflicts with an owner claim"); + } + + private void requireTenantBinding(AuthoredWorldSourceEvidence receipt) { + Record binding = + dsl.selectFrom(TENANT_SLUG_BINDING) + .where( + BINDING_NAMESPACE + .eq(receipt.targetNamespace()) + .and(BINDING_CANONICAL_TENANT_ID.eq(receipt.canonicalTenantId()))) + .fetchOne(); + if (binding == null) { + throw new InvalidSourceEvidenceException("Tenant selector binding is missing"); + } + requireMatchingBinding( + binding, + receipt.targetNamespace(), + receipt.tenantSlug(), + new GameSource( + receipt.sourceGameRowId(), + receipt.canonicalTenantId(), + receipt.sourceGameTenantKey(), + receipt.provenanceKind())); + } + + private void requireMatchingBinding( + Record binding, String targetNamespace, String tenantSlug, GameSource source) { + if (!targetNamespace.equals(binding.get(BINDING_NAMESPACE)) + || !source.canonicalTenantId().equals(binding.get(BINDING_CANONICAL_TENANT_ID)) + || !tenantSlug.equals(binding.get(BINDING_TENANT_SLUG)) + || source.sourceGameRowId() != binding.get(BINDING_SOURCE_GAME_ROW_ID) + || !source.sourceGameTenantKey().equals(binding.get(BINDING_SOURCE_GAME_TENANT_KEY)) + || !source.provenanceKind().equals(binding.get(BINDING_PROVENANCE_KIND))) { + throw new RegistrationConflictException( + "Canonical tenant already has a different stable tenant selector or source tuple"); + } + } + + private Record findByRegistrationRequest(String targetNamespace, UUID registrationRequestId) { + return dsl.selectFrom(OPERATION) + .where( + OPERATION_NAMESPACE + .eq(targetNamespace) + .and(REGISTRATION_REQUEST_ID.eq(registrationRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + return dsl.selectFrom(OPERATION) + .where( + OPERATION_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private GameSource lockGameSource(UUID canonicalTenantId) { + Record row = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .forUpdate() + .fetchOne(); + return row == null ? null : gameSource(row); + } + + private GameSource findGameSourceByRow(long sourceGameRowId) { + Record row = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_ID.eq(sourceGameRowId)) + .fetchOne(); + return row == null ? null : gameSource(row); + } + + private GameSource gameSource(Record row) { + Long id = row.get(GAME_ID); + String tenantKey = row.get(GAME_TENANT_ID); + UUID canonicalTenantId = row.get(GAME_CANONICAL_TENANT_ID); + String provenanceKind = row.get(GAME_PROVENANCE_KIND); + Long provenanceRowId = row.get(GAME_SOURCE_ROW_ID); + String provenanceTenantKey = row.get(GAME_SOURCE_TENANT_KEY); + if (id == null + || tenantKey == null + || canonicalTenantId == null + || provenanceKind == null + || provenanceRowId == null + || provenanceTenantKey == null + || !id.equals(provenanceRowId) + || !tenantKey.equals(provenanceTenantKey)) { + throw new InvalidSourceEvidenceException( + "Game Design tenant source provenance does not match its game row"); + } + return new GameSource(id, canonicalTenantId, tenantKey, provenanceKind); + } + + private void requireConsistentGameSource(GameSource source) { + if (!NEW_GAME_ROW.equals(source.provenanceKind()) + && !RETAINED_GAME_V29.equals(source.provenanceKind())) { + throw new InvalidSourceEvidenceException("Game Design tenant provenance is not recognized"); + } + } + + private void requireReceiptSource(AuthoredWorldSourceEvidence receipt, GameSource source) { + if (receipt.sourceGameRowId() != source.sourceGameRowId() + || !receipt.canonicalTenantId().equals(source.canonicalTenantId()) + || !receipt.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !receipt.provenanceKind().equals(source.provenanceKind())) { + throw new InvalidSourceEvidenceException( + "Authored-world source tuple no longer matches its Game Design row"); + } + } + + private AuthoredWorldSourceEvidence toEvidence(Record row) { + try { + return new AuthoredWorldSourceEvidence( + row.get(OPERATION_SCHEMA_VERSION), + row.get(OPERATION_NAMESPACE), + row.get(REGISTRATION_REQUEST_ID), + row.get(OPERATION_ID), + row.get(REQUEST_DIGEST), + row.get(CANONICAL_TENANT_ID), + row.get(TENANT_SLUG), + row.get(WORLD_SLUG), + row.get(WORLD_DISPLAY_NAME), + row.get(SOURCE_GAME_ROW_ID), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(PROVENANCE_KIND), + row.get(EVIDENCE_DIGEST)); + } catch (RuntimeException exception) { + throw new InvalidSourceEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source registration requires an active Game Design owner transaction"); + } + } + + private record GameSource( + long sourceGameRowId, + UUID canonicalTenantId, + String sourceGameTenantKey, + String provenanceKind) {} + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidSourceEvidenceException extends IllegalStateException { + public InvalidSourceEvidenceException(String message) { + super(message); + } + + public InvalidSourceEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index bc08758690..e389eec181 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -11,10 +11,13 @@ import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; @@ -25,6 +28,8 @@ import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyKind; import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryStateScope; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; @@ -53,6 +58,7 @@ public class TenantIdentityGrpcService private final GameRepository gameRepository; private final GameSessionTenantAssociationRepository gameSessionAssociationRepository; private final PublishedReleaseBundleService publishedReleaseBundleService; + private final GameAuthoredWorldSourceRepository authoredWorldRepository; private final String workloadNamespace; private final ObjectMapper objectMapper; @@ -62,13 +68,15 @@ public TenantIdentityGrpcService( GameSessionTenantAssociationRepository gameSessionAssociationRepository, PublishedReleaseBundleService publishedReleaseBundleService, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, + GameAuthoredWorldSourceRepository authoredWorldRepository) { this.creationRepository = creationRepository; this.gameRepository = gameRepository; this.gameSessionAssociationRepository = gameSessionAssociationRepository; this.publishedReleaseBundleService = publishedReleaseBundleService; this.workloadNamespace = workloadNamespace; this.objectMapper = objectMapper; + this.authoredWorldRepository = authoredWorldRepository; } @Override @@ -650,6 +658,102 @@ private ResolvePublishedRealmEntryPolicyResponse toPolicyResponse( .build(); } + @Override + public void resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (!isAuthoredWorldSourceReaderPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified same-namespace Game Session or World Management identity is required") + .asRuntimeException()); + return; + } + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID operationId = parseCanonicalNonNilUuid(request.getOperationId()); + UUID tenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + try { + if (requestId == null + || operationId == null + || tenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact source request is required"); + } + AuthoredWorldSourceDigest.validateReadSelector( + workloadNamespace, tenantId, request.getWorldSlug()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical exact source request is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = + authoredWorldRepository.read( + operationId, tenantId, request.getWorldSlug(), workloadNamespace); + } catch (IllegalArgumentException | IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source evidence is inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Authored-world source is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription("Authored-world source could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No authored-world source for the exact operation and scope") + .asRuntimeException()); + return; + } + AuthoredWorldSourceEvidence evidence = resolved.orElseThrow(); + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !operationId.equals(evidence.operationId()) + || !tenantId.equals(evidence.canonicalTenantId()) + || !request.getWorldSlug().equals(evidence.worldSlug())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source readback does not match the request") + .asRuntimeException()); + return; + } + responseObserver.onNext( + ResolveAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(requestId.toString()) + .setRegistrationRequestId(evidence.registrationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setTenantSlug(evidence.tenantSlug()) + .setWorldSlug(evidence.worldSlug()) + .setWorldDisplayName(evidence.worldDisplayName()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build()); + responseObserver.onCompleted(); + } + private boolean isGameSessionPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null @@ -665,6 +769,15 @@ private boolean isAccountPeer() { && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); } + private boolean isAuthoredWorldSourceReaderPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && (peer.uri().equals(expectedPrefix + "game-session-service") + || peer.uri().equals(expectedPrefix + "world-management-service")); + } + private static UUID parseCanonicalNonNilUuid(String value) { if (value == null) { return null; diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index eb2367f629..e78bc07082 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -55,6 +55,7 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolvePublishedRealmEntryPolicy - gamedesign.v1.TenantIdentityService/ListPublishedRealmEntryPolicies - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 0cd1247241..097768fb14 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -66,6 +66,7 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolvePublishedRealmEntryPolicy - gamedesign.v1.TenantIdentityService/ListPublishedRealmEntryPolicies - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql new file mode 100644 index 0000000000..61da5a5085 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql @@ -0,0 +1,224 @@ +CREATE TABLE game_design_tenant_slug_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_tenant_slug_binding PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_tenant_slug_binding_slug UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gd_tenant_slug_binding_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gd_tenant_slug_binding_source UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_tenant_slug_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_tenant_slug_binding_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_tenant_slug_binding_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +CREATE TABLE game_design_authored_world_source_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL CHECK (schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_authored_world_request UNIQUE (target_namespace, registration_request_id), + CONSTRAINT uq_gd_authored_world_selector UNIQUE ( + target_namespace, + canonical_tenant_id, + world_slug + ), + CONSTRAINT fk_gd_authored_world_tenant_binding FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ) REFERENCES game_design_tenant_slug_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gd_authored_world_operation_id CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_request_id CHECK ( + registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_tenant_id CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_world_digest_shape CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_world_tenant_slug CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_world_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_authored_world_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_tenant_slug_binding() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design tenant selector binding is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design tenant selector source does not match its game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_tenant_slug_binding + FOR EACH ROW EXECUTE FUNCTION enforce_gd_tenant_slug_binding(); + +CREATE FUNCTION enforce_gd_authored_world_source() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = NEW.target_namespace + AND b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.tenant_slug = NEW.tenant_slug + AND b.source_game_row_id = NEW.source_game_row_id + AND b.source_game_tenant_key = NEW.source_game_tenant_key + AND b.provenance_kind = NEW.provenance_kind + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world source does not match its owner row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source(); + +CREATE FUNCTION require_gd_tenant_slug_source() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + WHERE o.target_namespace = NEW.target_namespace + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Design tenant selector claim cannot commit without a world source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER gd_tenant_slug_binding_requires_source + AFTER INSERT ON game_design_tenant_slug_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_gd_tenant_slug_source(); + +CREATE FUNCTION reject_gd_authored_world_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_tenant_slug_binding_no_truncate + BEFORE TRUNCATE ON game_design_tenant_slug_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); + +CREATE TRIGGER gd_authored_world_source_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V34.2__world_authored_source_delivery.sql b/services/game-design-service/src/main/resources/db/migration/V34.2__world_authored_source_delivery.sql new file mode 100644 index 0000000000..90883b945b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34.2__world_authored_source_delivery.sql @@ -0,0 +1,249 @@ +ALTER TABLE game_design_authored_world_source_operations + ADD CONSTRAINT uq_gd_authored_world_source_delivery_source UNIQUE ( + operation_id, + schema_version, + target_namespace, + registration_request_id, + request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +CREATE TABLE game_design_authored_world_source_deliveries ( + source_operation_id UUID PRIMARY KEY, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_schema_version INTEGER NOT NULL CHECK (intake_schema_version = 1), + intake_request_id UUID NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + world_operation_id UUID, + world_request_digest VARCHAR(71), + world_receipt_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + acknowledged_at TIMESTAMPTZ, + CONSTRAINT uq_gd_authored_world_source_delivery_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT fk_gd_authored_world_source_delivery_source FOREIGN KEY ( + source_operation_id, + source_schema_version, + target_namespace, + registration_request_id, + source_request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + source_evidence_digest + ) REFERENCES game_design_authored_world_source_operations ( + operation_id, + schema_version, + target_namespace, + registration_request_id, + request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ), + CONSTRAINT chk_gd_authored_world_source_delivery_fresh CHECK ( + provenance_kind = 'NEW_GAME_ROW' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_ids CHECK ( + source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_game_row_id > 0 + ), + CONSTRAINT chk_gd_authored_world_source_delivery_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_digests CHECK ( + source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (world_operation_id IS NULL + AND world_request_digest IS NULL + AND world_receipt_digest IS NULL + AND acknowledged_at IS NULL) + OR + (world_operation_id IS NOT NULL + AND world_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_request_digest IS NOT NULL + AND world_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_receipt_digest IS NOT NULL + AND world_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND acknowledged_at IS NOT NULL) + ) + ), + CONSTRAINT chk_gd_authored_world_source_delivery_slugs CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_authored_world_source_delivery() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design authored-world source delivery is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.world_operation_id IS NOT NULL + OR NEW.world_request_digest IS NOT NULL + OR NEW.world_receipt_digest IS NOT NULL + OR NEW.acknowledged_at IS NOT NULL THEN + RAISE EXCEPTION 'New Game Design authored-world delivery cannot start acknowledged' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = o.target_namespace + AND b.canonical_tenant_id = o.canonical_tenant_id + AND b.tenant_slug = o.tenant_slug + AND b.source_game_row_id = o.source_game_row_id + AND b.source_game_tenant_key = o.source_game_tenant_key + AND b.provenance_kind = o.provenance_kind + JOIN game g + ON g.id = o.source_game_row_id + AND g.tenant_id = o.source_game_tenant_key + AND g.canonical_tenant_id = o.canonical_tenant_id + AND g.tenant_identity_provenance_kind = o.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE o.operation_id = NEW.source_operation_id + AND o.schema_version = NEW.source_schema_version + AND o.target_namespace = NEW.target_namespace + AND o.registration_request_id = NEW.registration_request_id + AND o.request_digest = NEW.source_request_digest + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.world_slug = NEW.world_slug + AND o.world_display_name = NEW.world_display_name + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = 'NEW_GAME_ROW' + AND o.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world delivery has no exact fresh source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF ROW( + NEW.source_operation_id, + NEW.source_schema_version, + NEW.target_namespace, + NEW.registration_request_id, + NEW.source_request_digest, + NEW.canonical_tenant_id, + NEW.tenant_slug, + NEW.world_slug, + NEW.world_display_name, + NEW.source_game_row_id, + NEW.source_game_tenant_key, + NEW.provenance_kind, + NEW.source_evidence_digest, + NEW.intake_schema_version, + NEW.intake_request_id, + NEW.intake_request_digest, + NEW.created_at + ) IS DISTINCT FROM ROW( + OLD.source_operation_id, + OLD.source_schema_version, + OLD.target_namespace, + OLD.registration_request_id, + OLD.source_request_digest, + OLD.canonical_tenant_id, + OLD.tenant_slug, + OLD.world_slug, + OLD.world_display_name, + OLD.source_game_row_id, + OLD.source_game_tenant_key, + OLD.provenance_kind, + OLD.source_evidence_digest, + OLD.intake_schema_version, + OLD.intake_request_id, + OLD.intake_request_digest, + OLD.created_at + ) THEN + RAISE EXCEPTION 'Game Design authored-world delivery claim cannot be rebound' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.world_operation_id IS NULL + AND OLD.world_request_digest IS NULL + AND OLD.world_receipt_digest IS NULL + AND OLD.acknowledged_at IS NULL + AND NEW.world_operation_id IS NOT NULL + AND NEW.world_request_digest IS NOT NULL + AND NEW.world_receipt_digest IS NOT NULL + AND NEW.acknowledged_at IS NOT NULL THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Game Design authored-world delivery acknowledgement is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_delivery_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_deliveries + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source_delivery(); + +CREATE FUNCTION reject_gd_authored_world_source_delivery_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source delivery is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_delivery_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_deliveries + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_source_delivery_truncate(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java new file mode 100644 index 0000000000..09134c7feb --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -0,0 +1,624 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceDeliveryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-delivery-test"; + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("34.1"); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("11111111-1111-4111-8111-111111111111"); + + AuthoredWorldSourceEvidence source = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim firstClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + AuthoredWorldSourceEvidence retry = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim retryClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + + assertThat(firstClaim.source()).isEqualTo(source); + assertThat(firstClaim.request().schemaVersion()).isEqualTo(1); + assertThat(firstClaim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(firstClaim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(firstClaim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(firstClaim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(firstClaim.request().expectedSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + assertThat(firstClaim.request().intakeRequestId()).isNotEqualTo(source.operationId()); + assertThat(retry).isEqualTo(source); + assertThat(retryClaim).isEqualTo(firstClaim); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + } + + @Test + void pendingDeliveryPagesAreNamespaceBoundKeysetOrderedAndExcludeAcknowledgedClaims() { + Fixture fixture = fixture(null); + String otherNamespace = "other-authored-world-delivery-test"; + AuthoredWorldSourceEvidence firstNamespaceSource = + fixture.register( + NAMESPACE, + uuid("12121212-1212-4212-8212-121212121212"), + fixture.freshGame(), + "pending-tenant-one", + "pending-world-one"); + AuthoredWorldSourceEvidence secondNamespaceSource = + fixture.register( + NAMESPACE, + uuid("13131313-1313-4313-8313-131313131313"), + fixture.createFreshGame(), + "pending-tenant-two", + "pending-world-two"); + AuthoredWorldSourceEvidence otherNamespaceSource = + fixture.register( + otherNamespace, + uuid("14141414-1414-4414-8414-141414141414"), + fixture.freshGame(), + "other-pending-tenant", + "other-pending-world"); + + var firstPage = fixture.deliveryRepository().readPending(NAMESPACE, null, 1); + var secondPage = + fixture + .deliveryRepository() + .readPending(NAMESPACE, firstPage.get(0).request().intakeRequestId(), 1); + var otherNamespacePage = fixture.deliveryRepository().readPending(otherNamespace, null, 10); + + assertThat(firstPage).hasSize(1); + assertThat(secondPage).hasSize(1); + assertThat(firstPage.get(0).source().operationId()) + .isNotEqualTo(secondPage.get(0).source().operationId()); + assertThat( + List.of( + firstPage.get(0).source().operationId(), secondPage.get(0).source().operationId())) + .containsExactlyInAnyOrder( + firstNamespaceSource.operationId(), secondNamespaceSource.operationId()); + assertThat(otherNamespacePage) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo(otherNamespaceSource.operationId()); + + DeliveryClaim pending = firstPage.get(0); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("15151515-1515-4515-8515-151515151515"), 'a'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + + assertThat(acknowledged).isNotNull(); + assertThat(fixture.deliveryRepository().readPending(NAMESPACE, null, 10)) + .singleElement() + .extracting(claim -> claim.source().operationId()) + .isEqualTo( + firstNamespaceSource.operationId().equals(pending.source().operationId()) + ? secondNamespaceSource.operationId() + : firstNamespaceSource.operationId()); + } + + @Test + void sourceAndDeliveryIntentRollBackTogether() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); + AtomicReference sourceRef = new AtomicReference<>(); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) + .hasMessageContaining("simulate failed source owner commit"); + + AuthoredWorldSourceEvidence attempted = sourceRef.get(); + assertThat(attempted).isNotNull(); + assertThat( + fixture + .sourceRepository() + .read( + attempted.operationId(), + attempted.canonicalTenantId(), + attempted.worldSlug(), + attempted.targetNamespace())) + .isEmpty(); + assertThat(fixture.deliveryRepository().read(attempted.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(44); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("55555555-5555-4555-8555-555555555555"), 'c'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + assertThat(acknowledged).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("claim cannot be rebound"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("acknowledgement is immutable"); + assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) + .isEqualTo(acknowledged); + } + + @Test + void retainedSourceAndGameRowsRemainUnchangedAcrossV34_2WithoutDeliveryAssociation() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + Map retainedGameBefore = + gameSnapshot(fixture.dsl(), fixture.retainedGameRowId()); + UUID registrationRequestId = uuid("77777777-7777-4777-8777-777777777777"); + AuthoredWorldSourceEvidence retainedSource = + fixture.register( + registrationRequestId, + fixture.retainedCanonicalTenantId(), + "retained-tenant", + "old-coast", + "Retained Coast"); + Map retainedSourceBefore = + sourceSnapshot(fixture.dsl(), retainedSource.operationId()); + Map retainedBindingBefore = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding before V34.2 migration") + .intoMap(); + + fixture.migrate(null); + + assertThat(gameSnapshot(fixture.dsl(), fixture.retainedGameRowId())) + .isEqualTo(retainedGameBefore); + assertThat(sourceSnapshot(fixture.dsl(), retainedSource.operationId())) + .isEqualTo(retainedSourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding after V34.2 migration") + .intoMap()) + .isEqualTo(retainedBindingBefore); + assertThat( + fixture + .sourceRepository() + .read( + retainedSource.operationId(), + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.targetNamespace())) + .contains(retainedSource); + assertThat(fixture.deliveryRepository().read(retainedSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void historicalFreshSourceRetryDoesNotBackfillMissingV34_2DeliveryClaim() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + UUID registrationRequestId = uuid("88888888-8888-4888-8888-888888888888"); + String tenantSlug = "historic-tenant"; + String worldSlug = "historic-world"; + String displayName = "Historical Fresh World"; + AuthoredWorldSourceEvidence historicalSource = + seedPreDeliverySource( + fixture, + fixture.freshGame(), + registrationRequestId, + tenantSlug, + worldSlug, + displayName); + + fixture.migrate(null); + + AuthoredWorldSourceEvidence exactRetry = + fixture.register( + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + assertThat(exactRetry).isEqualTo(historicalSource); + assertThat(fixture.deliveryRepository().read(historicalSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(GAME_TENANT_ID, "retained-delivery-source") + .set(GAME_NAME, "Retained Delivery Source") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + migrate(dataSource, schema, target); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(dsl); + GameAuthoredWorldSourceRepository sourceRepository = + new GameAuthoredWorldSourceRepository(dsl, deliveryRepository); + GameRepository gameRepository = new GameRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(GAME_CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(GAME_CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId(UUID.randomUUID().toString()); + freshGame.setName("Fresh Delivery Source"); + freshGame.setDescription("Created through the current Game Design owner repository"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + sourceRepository, + deliveryRepository, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private static void migrate( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + Path gameDesignMigrations = + repositoryRoot().resolve("services/game-design-service/src/main/resources/db/migration"); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + gameDesignMigrations); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private AuthoredWorldSourceEvidence seedPreDeliverySource( + Fixture fixture, + Game game, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW")); + + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private static CommittedReceipt committedReceipt( + IntakeRequest request, UUID worldOperationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static Map gameSnapshot(DSLContext dsl, long gameRowId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id, " + + "xmin::text AS xmin FROM game WHERE id = ?", + gameRowId), + "Expected game snapshot for row " + gameRowId) + .intoMap(); + } + + private static Map sourceSnapshot(DSLContext dsl, UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + operationId), + "Expected authored-world source snapshot for operation " + operationId) + .intoMap(); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameAuthoredWorldSourceRepository sourceRepository, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + Game freshGame) { + AuthoredWorldSourceEvidence registerFresh(int suffix) { + return register( + uuid(String.format("%08d-1111-4111-8111-111111111111", suffix)), + freshGame, + "fresh-tenant-" + suffix, + "fresh-world-" + suffix); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, Game sourceGame, String tenantSlug, String worldSlug) { + return register(NAMESPACE, registrationRequestId, sourceGame, tenantSlug, worldSlug); + } + + AuthoredWorldSourceEvidence register( + String targetNamespace, + UUID registrationRequestId, + Game sourceGame, + String tenantSlug, + String worldSlug) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + targetNamespace, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); + return java.util.Objects.requireNonNull(source); + } + + Game createFreshGame() { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Additional Fresh Delivery Source"); + game.setDescription("A second isolated fresh tenant source for pending paging"); + return Objects.requireNonNull( + transactionTemplate.execute(status -> new GameRepository(dsl).save(game))); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(source); + } + + void migrate(MigrationVersion target) { + GameAuthoredWorldSourceDeliveryIntegrationTest.migrate(dataSource, schema, target); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4382f496c0 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -0,0 +1,617 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameAuthoredWorldSourceRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-test"; + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final org.jooq.Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void registersAndReadsExactFreshAndRetainedV28ToV29Sources() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + + AuthoredWorldSourceEvidence retainedReceipt = + fixture.register( + uuid(1), fixture.retainedCanonicalTenantId(), "old-kingdom", "ember-coast", "Café 🐉"); + AuthoredWorldSourceEvidence freshReceipt = + fixture.register( + uuid(2), + fixture.freshCanonicalTenantId(), + "new-kingdom", + "silver-march", + "Silver March"); + + assertThat(retainedReceipt.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThat(retainedReceipt.sourceGameRowId()).isEqualTo(fixture.retainedGameRowId()); + assertThat(retainedReceipt.sourceGameTenantKey()).isEqualTo("retained-authored-tenant"); + assertThat(freshReceipt.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(freshReceipt.sourceGameRowId()).isEqualTo(fixture.freshGameRowId()); + assertThat(freshReceipt.sourceGameTenantKey()).isEqualTo("fresh-authored-tenant"); + assertThat( + fixture.repository.read( + retainedReceipt.operationId(), + retainedReceipt.canonicalTenantId(), + retainedReceipt.worldSlug(), + retainedReceipt.targetNamespace())) + .contains(retainedReceipt); + assertThat( + fixture.repository.read( + freshReceipt.operationId(), + freshReceipt.canonicalTenantId(), + freshReceipt.worldSlug(), + freshReceipt.targetNamespace())) + .contains(freshReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID requestId = uuid(10); + AuthoredWorldSourceEvidence original = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + String gameXmin = gameXmin(fixture.dsl, "fresh-authored-tenant"); + + AuthoredWorldSourceEvidence retry = + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "First World"); + assertThat(retry).isEqualTo(original); + assertThat( + fixture.repository.read( + original.operationId(), + original.canonicalTenantId(), + original.worldSlug(), + original.targetNamespace())) + .contains(original); + + assertThatThrownBy( + () -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("reused with changed input"); + assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + + @Test + void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> + fixture.repository.read( + uuid(12), + fixture.freshCanonicalTenantId(), + "transaction-world", + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + fixture.register( + uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); + + assertThatThrownBy( + () -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + + assertThatThrownBy( + () -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) + .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) + .hasMessageContaining("selector is already owned"); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(2); + } + + @Test + void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed owner commit"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + assertThat( + fixture.register( + uuid(31), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")) + .isNotNull(); + } + + @Test + void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("cannot commit without a world source"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + assertThatThrownBy( + () -> + fixture.transactionTemplate.execute( + status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set( + DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its game row"); + + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + } + + @Test + void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + AuthoredWorldSourceEvidence receipt = + fixture.register( + uuid(40), fixture.freshCanonicalTenantId(), "read-tenant", "read-world", "Read World"); + + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + "different-world", + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + fixture.retainedCanonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .isEmpty(); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + "other-namespace")) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("binding is immutable"); + assertThat( + fixture.repository.read( + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.targetNamespace())) + .contains(receipt); + } + + @Test + void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + Future second = + executor.submit( + () -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AuthoredWorldSourceEvidence firstReceipt = first.get(10, TimeUnit.SECONDS); + AuthoredWorldSourceEvidence secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), + firstReceipt.canonicalTenantId(), + firstReceipt.worldSlug(), + firstReceipt.targetNamespace())) + .contains(firstReceipt); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { + Fixture fixture = fixtureWithRetainedAndFreshGame(); + UUID secondCanonicalTenantId = fixture.createFreshGame("second-fresh-authored-tenant"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freshTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); + Future secondTenant = + executor.submit( + () -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat( + java.util.List.of( + freshTenant.get(10, TimeUnit.SECONDS), secondTenant.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(RegistrationOutcome.CREATED, RegistrationOutcome.CONFLICT); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(3); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private RegistrationOutcome raceRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + try { + fixture.register( + registrationRequestId, canonicalTenantId, tenantSlug, worldSlug, "Racing World"); + return RegistrationOutcome.CREATED; + } catch (GameAuthoredWorldSourceRepository.RegistrationConflictException conflict) { + return RegistrationOutcome.CONFLICT; + } + } + + private AuthoredWorldSourceEvidence concurrentRegister( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + UUID registrationRequestId, + String tenantSlug, + String worldSlug) { + ready.countDown(); + await(start); + return fixture.register( + registrationRequestId, + fixture.freshCanonicalTenantId(), + tenantSlug, + worldSlug, + "Concurrent World"); + } + + private Fixture fixtureWithRetainedAndFreshGame() { + String schema = "game_design_authored_world_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-authored-tenant") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameAuthoredWorldSourceRepository repository = new GameAuthoredWorldSourceRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId("fresh-authored-tenant"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Created after canonical tenant identity"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + dsl, + repository, + gameRepository, + transactionTemplate, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame.getId(), + persistedFreshGame.getCanonicalTenantId()); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private String gameXmin(DSLContext dsl, String tenantKey) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE tenant_id = ?", tenantKey) + .getFirst() + .get("xmin", String.class); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent registration"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent registration", exception); + } + } + + private enum RegistrationOutcome { + CREATED, + CONFLICT + } + + private record Fixture( + DSLContext dsl, + GameAuthoredWorldSourceRepository repository, + GameRepository gameRepository, + TransactionTemplate transactionTemplate, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + long freshGameRowId, + UUID freshCanonicalTenantId) { + AuthoredWorldSourceEvidence register( + UUID requestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence receipt = + transactionTemplate.execute( + status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(receipt); + } + + UUID createFreshGame(String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName(tenantKey); + game.setDescription("Concurrent source fixture"); + Game persisted = transactionTemplate.execute(status -> gameRepository.save(game)); + return java.util.Objects.requireNonNull(persisted).getCanonicalTenantId(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index 31bc72e2a2..cf3602bedf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -34,8 +34,11 @@ import net.firedevops.firemud.common.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; @@ -46,6 +49,8 @@ import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; import net.firedevops.firemud.gamedesign.v1.PingRequest; import net.firedevops.firemud.gamedesign.v1.PingResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; @@ -69,6 +74,192 @@ import tools.jackson.databind.ObjectMapper; class TenantIdentityGrpcAuthWiringTest { + private static final String SOURCE_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"; + private static final MethodDescriptor< + ResolveAuthoredWorldSourceRequest, ResolveAuthoredWorldSourceResponse> + SOURCE_METHOD_DESCRIPTOR = + unaryMethod( + SOURCE_METHOD, + ResolveAuthoredWorldSourceRequest.getDefaultInstance(), + ResolveAuthoredWorldSourceResponse.getDefaultInstance()); + + @Test + void noTokenWithExactWorldOrGameSessionPeerReachesOnlyAuthoredSourceRead() { + withConfiguredInterceptor( + interceptor -> { + GameAuthoredWorldSourceRepository repository = + mock(GameAuthoredWorldSourceRepository.class); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameTenantCreationRepository.class), + mock(GameRepository.class), + mock(GameSessionTenantAssociationRepository.class), + mock( + net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService + .class), + "test", + new tools.jackson.databind.ObjectMapper(), + repository); + AuthoredWorldSourceEvidence evidence = authoredSourceEvidence("test"); + when(repository.read( + UUID.fromString(REQUEST_UUID), UUID.fromString(TENANT_UUID), "world-one", "test")) + .thenReturn(Optional.of(evidence)); + for (String peer : + List.of(GAME_SESSION_URI, "spiffe://firemud/ns/test/sa/world-management-service")) { + SourceDispatchResult result = dispatchSourceMethod(interceptor, service, peer); + assertThat(result.handlerDispatched()).isTrue(); + assertThat(result.observer().failure).isFalse(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getEvidenceDigest()) + .isEqualTo(evidence.evidenceDigest()); + } + }); + } + + @Test + void allowlistedAuthoredSourceReadDeniesAbsentWrongServiceAndWrongNamespaceBeforeOwnerAccess() { + withConfiguredInterceptor( + interceptor -> { + GameAuthoredWorldSourceRepository repository = + mock(GameAuthoredWorldSourceRepository.class); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameTenantCreationRepository.class), + mock(GameRepository.class), + mock(GameSessionTenantAssociationRepository.class), + mock( + net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService + .class), + "test", + new tools.jackson.databind.ObjectMapper(), + repository); + for (String peer : + new String[] { + null, + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/world-management-service" + }) { + SourceDispatchResult result = dispatchSourceMethod(interceptor, service, peer); + assertThat(result.handlerDispatched()).isTrue(); + assertThat(result.observer().statusCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(result.observer().response).isNull(); + } + verifyNoInteractions(repository); + }); + } + + private static SourceDispatchResult dispatchSourceMethod( + AuthTokenInterceptor interceptor, TenantIdentityGrpcService service, String peerUri) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(SOURCE_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + SourceObserver observer = new SourceObserver(); + ServerCallHandler next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ResolveAuthoredWorldSourceRequest request) { + service.resolveAuthoredWorldSource(request, observer); + } + }; + } + }; + ResolveAuthoredWorldSourceRequest request = + ResolveAuthoredWorldSourceRequest.newBuilder() + .setOperationId(REQUEST_UUID) + .setWorldSlug("world-one") + .setCanonicalTenantId(TENANT_UUID) + .setRequestId(REQUEST_UUID) + .build(); + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new SourceDispatchResult(observer, handlerDispatched.get()); + } + + private static AuthoredWorldSourceEvidence authoredSourceEvidence(String namespace) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString(TENANT_UUID), + "tenant-one", + "world-one", + "Wörld"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString(REQUEST_UUID), + requestDigest, + UUID.fromString(TENANT_UUID), + "tenant-one", + "world-one", + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString(REQUEST_UUID), + requestDigest, + UUID.fromString(TENANT_UUID), + "tenant-one", + "world-one", + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static final class SourceObserver + implements StreamObserver { + private ResolveAuthoredWorldSourceResponse response; + private Status.Code statusCode; + private boolean failure; + private boolean completed; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = true; + statusCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private record SourceDispatchResult(SourceObserver observer, boolean handlerDispatched) {} + private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; private static final String TENANT_METHOD = @@ -128,7 +319,8 @@ void noTokenWithValidSameNamespacePeerReachesTenantIdentityService() { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); DispatchResult result = dispatchTenantMethod(interceptor, service, GAME_SESSION_URI); @@ -179,7 +371,8 @@ void noTokenWithValidSameNamespacePeerReachesPublishedRealmPolicyRead() { mock(GameSessionTenantAssociationRepository.class), publishedReleaseBundleService, "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); PolicyDispatchResult result = dispatchRealmPolicyMethod(interceptor, service, GAME_SESSION_URI); @@ -243,7 +436,8 @@ void noTokenWithValidSameNamespacePeerReachesCompleteRealmPolicySetRead() { mock(GameSessionTenantAssociationRepository.class), publishedReleaseBundleService, "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); PolicySetDispatchResult result = dispatchRealmPolicySetMethod(interceptor, service, GAME_SESSION_URI); @@ -272,7 +466,8 @@ void publishedRealmPolicyMethodIsDeniedBeforeOwnerReadForWrongPeer() { mock(GameSessionTenantAssociationRepository.class), publishedReleaseBundleService, "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); PolicyDispatchResult wrong = dispatchRealmPolicyMethod( @@ -298,7 +493,8 @@ void completeRealmPolicySetMethodIsDeniedBeforeOwnerReadForWrongPeer() { mock(GameSessionTenantAssociationRepository.class), publishedReleaseBundleService, "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); PolicySetDispatchResult wrong = dispatchRealmPolicySetMethod( @@ -323,7 +519,8 @@ void noTokenWithAbsentOrWrongPeerIsDeniedBeforeOwnerRead() { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); DispatchResult absent = dispatchTenantMethod(interceptor, service, null); DispatchResult wrong = @@ -541,7 +738,8 @@ private static void withConfiguredInterceptor( ASSOCIATION_METHOD, REALM_POLICY_METHOD, REALM_POLICY_SET_METHOD, - FRESH_CREATION_METHOD); + FRESH_CREATION_METHOD, + SOURCE_METHOD); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } @@ -577,7 +775,8 @@ void productionConfigurationExemptsExactlyTheOwnerReadMethods() throws IOExcepti ASSOCIATION_METHOD, REALM_POLICY_METHOD, REALM_POLICY_SET_METHOD, - FRESH_CREATION_METHOD)); + FRESH_CREATION_METHOD, + SOURCE_METHOD)); } private static @@ -696,7 +895,8 @@ void defaultAndProductionProfilesAllowOwnerReadsAndRequireClientTls() throws IOE ASSOCIATION_METHOD, REALM_POLICY_METHOD, REALM_POLICY_SET_METHOD, - FRESH_CREATION_METHOD); + FRESH_CREATION_METHOD, + SOURCE_METHOD); assertThat(config.clientAuth()).isEqualTo("REQUIRE"); } } @@ -713,7 +913,8 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); FreshTenantCreationEvidence evidence = evidence("test", REQUEST_DIGEST); when(repository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); @@ -734,7 +935,8 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); when(gameSessionRepository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); DispatchResult gameSession = @@ -755,7 +957,8 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); DispatchResult unauthorized = dispatch( interceptor, @@ -836,7 +1039,8 @@ private static void withConfiguredInterceptor(Consumer act ASSOCIATION_METHOD, REALM_POLICY_METHOD, REALM_POLICY_SET_METHOD, - FRESH_CREATION_METHOD); + FRESH_CREATION_METHOD, + SOURCE_METHOD); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java new file mode 100644 index 0000000000..0a0cbbe634 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceMtlsTest.java @@ -0,0 +1,861 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.ManagedChannel; +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.NettyChannelBuilder; +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.MetadataUtils; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +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.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; + +/** + * Physical socket proof for Game Design's authored-world source reads. + * + *

The production gRPC service, peer-identity interceptor, JWT interceptor, and shared source + * client run over ephemeral mTLS sockets. Owner repositories are mocked and return complete, + * digest-valid evidence; this suite does not prove persistence, Account caller authorization or + * membership bootstrap, World intake, local association, publication, or runtime activation. + */ +class AuthoredWorldSourceMtlsTest { + private static final String NAMESPACE = "test"; + private static final String SOURCE_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"; + private static final String AUTHORIZATION = "authorization"; + private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static final Set TENANT_IDENTITY_JWT_BYPASS_METHODS = + Set.of( + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", + SOURCE_METHOD, + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation", + "gamedesign.v1.TenantIdentityService/ResolvePublishedRealmEntryPolicy", + "gamedesign.v1.TenantIdentityService/ListPublishedRealmEntryPolicies"); + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, READ_REQUEST_ID, SOURCE_OPERATION_ID, TENANT_ID, "harbor-world"); + private static TestPki pki; + + private GameRepository gameRepository; + private GameTenantCreationRepository creationRepository; + private GameAuthoredWorldSourceRepository authoredWorldRepository; + private GameSessionTenantAssociationRepository gameSessionAssociationRepository; + private Server server; + private AtomicReference responseMutation; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Authored Source Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null, false); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-workload", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-namespace", + "spiffe://firemud/ns/other-test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/test/sa/world-management-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-game-session-service", + "spiffe://firemud/ns/other-test/sa/game-session-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-account-service", + "spiffe://firemud/ns/other-test/sa/account-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "trusted-certificate-without-workload-uri", + null, + false)); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + gameRepository = mock(GameRepository.class); + creationRepository = mock(GameTenantCreationRepository.class); + authoredWorldRepository = mock(GameAuthoredWorldSourceRepository.class); + gameSessionAssociationRepository = mock(GameSessionTenantAssociationRepository.class); + when(authoredWorldRepository.read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE)) + .thenReturn(Optional.of(SOURCE_EVIDENCE)); + responseMutation = new AtomicReference<>(ResponseMutation.NONE); + server = startReceiver(pki.gameDesignServerCertificate()); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + stopServer(server); + server = null; + } + } + + @Test + void exactWorldAndGameSessionReadersResolveCompleteSourceReceiptThroughSharedClient( + @TempDir Path directory) throws Exception { + for (TestCertificate clientCertificate : + List.of(pki.worldManagementCertificate(), pki.gameSessionCertificate())) { + Path clientDirectory = directory.resolve(UUID.randomUUID().toString()); + AuthoredWorldSourceClient client = + newSharedClient(clientDirectory, server, clientCertificate); + try { + client.init(); + + assertThat(client.read(READ_REQUEST)).isEqualTo(SOURCE_EVIDENCE); + } finally { + client.close(); + } + } + + verify(authoredWorldRepository, times(2)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void wrongServiceNamespaceAndSharedCertificatesAreDeniedBeforeOwnerRead() throws Exception { + for (TestCertificate clientCertificate : + List.of( + pki.accountServiceCertificate(), + pki.wrongNamespaceCertificate(), + pki.noWorkloadUriCertificate())) { + ManagedChannel channel = channel(server, clientCertificate, jwtToken()); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeOwnerRead() throws Exception { + ManagedChannel channel = channel(server, null, null); + try { + assertTlsDenied( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), SOURCE_METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence() throws Exception { + ManagedChannel channel = channel(server, null, jwtToken()); + try { + assertTlsDenied( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), SOURCE_METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void validJwtWithTrustedCertificateButNoWorkloadUriIsDeniedByPeerGuard() throws Exception { + ManagedChannel channel = channel(server, pki.noWorkloadUriCertificate(), jwtToken()); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void sharedClientRefusesWrongGameDesignServerWorkloadAndNamespace(@TempDir Path directory) + throws Exception { + for (TestCertificate serverCertificate : + List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { + InboundRpcCapture inboundRpcCapture = new InboundRpcCapture(); + Server wrongIdentityServer = startReceiver(serverCertificate, inboundRpcCapture); + AuthoredWorldSourceClient client = + newSharedClient( + directory.resolve(UUID.randomUUID().toString()), + wrongIdentityServer, + pki.worldManagementCertificate()); + try { + client.init(); + assertServerPeerRefused(() -> client.read(READ_REQUEST)); + inboundRpcCapture.assertNoInboundRequests(); + } finally { + client.close(); + stopServer(wrongIdentityServer); + } + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void sharedClientRejectsChangedRequestEchoSourceDigestAndUnknownFieldsOverSocket( + @TempDir Path directory) throws Exception { + AuthoredWorldSourceClient client = + newSharedClient(directory, server, pki.worldManagementCertificate()); + try { + client.init(); + + responseMutation.set(ResponseMutation.CHANGE_READ_REQUEST_ID); + assertClientCodecRejected(() -> client.read(READ_REQUEST), "read request echo changed"); + + responseMutation.set(ResponseMutation.CHANGE_SOURCE_DISPLAY_NAME); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Request digest does not match the registration tuple"); + + responseMutation.set(ResponseMutation.CHANGE_EVIDENCE_DIGEST); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Evidence digest does not match the immutable tuple"); + + responseMutation.set(ResponseMutation.ADD_UNKNOWN_FIELD); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Authored-world source response contains unsupported"); + } finally { + client.close(); + } + + verify(authoredWorldRepository, times(4)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void unknownReadRequestFieldsAreRejectedByProductionServiceBeforeOwnerRead() throws Exception { + ManagedChannel channel = channel(server, pki.worldManagementCertificate(), jwtToken()); + ResolveAuthoredWorldSourceRequest unknownFieldRequest = + wireReadRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(unknownFieldRequest), + Status.Code.INVALID_ARGUMENT); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void productionYamlAndSocketGuardsKeepWorldAccessLimitedToExactSourceMethod() throws Exception { + for (String profile : List.of("application.yml", "application-prod.yml")) { + Set tenantIdentityBypassMethods = + publicMethods(profile).stream() + .filter(method -> method.startsWith("gamedesign.v1.TenantIdentityService/")) + .collect(java.util.stream.Collectors.toSet()); + assertThat(tenantIdentityBypassMethods) + .containsExactlyInAnyOrderElementsOf(TENANT_IDENTITY_JWT_BYPASS_METHODS); + } + + ManagedChannel channel = channel(server, pki.worldManagementCertificate(), jwtToken()); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = sourceStub(channel); + try { + assertStatus( + () -> + stub.resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveRuntimeTenantIdentity( + ResolveRuntimeTenantIdentityRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + assertStatus( + () -> + stub.resolveLegacyGameSessionTenantAssociation( + ResolveLegacyGameSessionTenantAssociationRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + + verifyNoInteractions( + gameRepository, + creationRepository, + authoredWorldRepository, + gameSessionAssociationRepository); + } + + private Server startReceiver(TestCertificate serverCertificate) throws Exception { + return startReceiver(serverCertificate, null); + } + + private Server startReceiver( + TestCertificate serverCertificate, InboundRpcCapture inboundRpcCapture) throws Exception { + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + creationRepository, + gameRepository, + gameSessionAssociationRepository, + mock(net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService.class), + NAMESPACE, + new tools.jackson.databind.ObjectMapper(), + authoredWorldRepository); + Set unauthenticatedMethods = publicMethods("application.yml"); + ServerInterceptor[] interceptors = + inboundRpcCapture == null + ? new ServerInterceptor[] { + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + } + : new ServerInterceptor[] { + inboundRpcCapture, + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, interceptors)) + .build() + .start(); + } + + private AuthoredWorldSourceClient newSharedClient( + Path directory, Server receiver, TestCertificate clientCertificate) throws Exception { + Files.createDirectories(directory); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + Path certificate = + writePem( + directory.resolve("client.crt"), + "CERTIFICATE", + clientCertificate.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("client.key"), + "PRIVATE KEY", + clientCertificate.privateKey().getEncoded()); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + receiver.getPort()); + return new AuthoredWorldSourceClient(endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private ManagedChannel channel(Server receiver, TestCertificate clientCertificate, String jwt) + throws Exception { + NettyChannelBuilder builder = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", receiver.getPort())) + .sslContext(clientSslContext(clientCertificate)); + if (jwt != null) { + Metadata headers = new Metadata(); + headers.put( + Metadata.Key.of(AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER), "Bearer " + jwt); + builder.intercept(MetadataUtils.newAttachHeadersInterceptor(headers)); + } + return builder.build(); + } + + private static io.grpc.netty.shaded.io.netty.handler.ssl.SslContext clientSslContext( + TestCertificate clientCertificate) throws Exception { + var builder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (clientCertificate != null) { + builder.keyManager(clientCertificate.privateKey(), clientCertificate.certificate()); + } + return builder.build(); + } + + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub sourceStub( + ManagedChannel channel) { + return TenantIdentityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private static ResolveAuthoredWorldSourceRequest wireReadRequest() { + return AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + } + + private String jwtToken() { + JwtUtil jwtUtil = new JwtUtil(JWT_SECRET, 60_000L); + return jwtUtil.generateToken( + "service:world-management-service", + Map.of( + "accountId", + "", + "globalRoles", + List.of(), + "scopedRoles", + Map.of(), + "internalService", + true, + "serviceName", + "world-management-service")); + } + + private static ServerInterceptor responseMutationInterceptor( + AtomicReference pendingMutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + super.sendMessage( + mutateResponse(message, pendingMutation.getAndSet(ResponseMutation.NONE))); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + @SuppressWarnings("unchecked") + private static Response mutateResponse(Response response, ResponseMutation mutation) { + if (mutation == ResponseMutation.NONE) { + return response; + } + if (!(response instanceof ResolveAuthoredWorldSourceResponse source)) { + throw new IllegalStateException("Response mutation does not match the source read RPC"); + } + return (Response) + switch (mutation) { + case CHANGE_READ_REQUEST_ID -> + source.toBuilder().setRequestId("55555555-5555-4555-8555-555555555555").build(); + case CHANGE_SOURCE_DISPLAY_NAME -> + source.toBuilder().setWorldDisplayName("Changed display name").build(); + case CHANGE_EVIDENCE_DIGEST -> + source.toBuilder().setEvidenceDigest("sha256:" + "f".repeat(64)).build(); + case ADD_UNKNOWN_FIELD -> + source.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + case NONE -> source; + }; + } + + private static void assertStatus(Runnable call, Status.Code expectedCode) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as("RPC should fail with %s: %s", expectedCode, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as("RPC denial evidence: %s", diagnostics(failure)) + .isEqualTo(expectedCode); + } + + private static void assertServerPeerRefused(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(Status.fromThrowable(failure).getDescription()) + .contains("exact authenticated server workload identity"); + } + + private static final class InboundRpcCapture implements ServerInterceptor { + private final AtomicInteger rpcCount = new AtomicInteger(); + private final AtomicInteger requestMessageCount = new AtomicInteger(); + private final AtomicReference methodName = new AtomicReference<>(); + private final AtomicReference requestMetadata = new AtomicReference<>(); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcCount.incrementAndGet(); + methodName.set(call.getMethodDescriptor().getFullMethodName()); + requestMetadata.set(headers); + ServerCall.Listener listener = next.startCall(call, headers); + return new SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + requestMessageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + private void assertNoInboundRequests() { + assertThat(rpcCount.get()).isZero(); + assertThat(requestMessageCount.get()).isZero(); + assertThat(methodName.get()).isNull(); + assertThat(requestMetadata.get()).isNull(); + } + } + + private static void assertClientCodecRejected(Runnable call, String expectedEvidence) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(diagnostics(failure)).contains(expectedEvidence); + } + + private static void assertTlsDenied(Runnable call, String method) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as( + "%s must fail with client-certificate handshake evidence: %s", + method, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as( + "%s must fail at TLS rather than by application timeout: %s", + method, diagnostics(failure)) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s cause chain must identify client-certificate rejection: %s", + method, diagnostics(failure)) + .isTrue(); + } + + private static Set publicMethods(String resourceName) throws IOException { + ConfigurableEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + for (var propertySource : + new YamlPropertySourceLoader() + .load(resourceName, new FileSystemResource("src/main/resources/" + resourceName))) { + environment.getPropertySources().addFirst(propertySource); + } + return Set.copyOf( + Binder.get(environment) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String tenantSlug = "firemud"; + String worldSlug = "harbor-world"; + String worldDisplayName = "Harbor World"; + String sourceGameTenantKey = "legacy-game-17"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static String diagnostics(Throwable throwable) { + if (throwable == null) { + return "RPC unexpectedly completed"; + } + StringBuilder result = new StringBuilder(); + for (Throwable current = throwable; current != null; current = current.getCause()) { + if (!result.isEmpty()) { + result.append(" <- "); + } + result.append(current.getClass().getName()).append(": ").append(current.getMessage()); + } + return result.toString(); + } + + private static TestCertificate issueLeaf( + X500Name caName, + PrivateKey caPrivateKey, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames), + serverCertificate); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames, + boolean serverCertificate) + throws Exception { + Instant now = Instant.now().minusSeconds(60L); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + serverCertificate ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private enum ResponseMutation { + NONE, + CHANGE_READ_REQUEST_ID, + CHANGE_SOURCE_DISPLAY_NAME, + CHANGE_EVIDENCE_DIGEST, + ADD_UNKNOWN_FIELD + } + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignServerCertificate, + TestCertificate wrongServerWorkloadCertificate, + TestCertificate wrongServerNamespaceCertificate, + TestCertificate worldManagementCertificate, + TestCertificate gameSessionCertificate, + TestCertificate accountServiceCertificate, + TestCertificate wrongNamespaceCertificate, + TestCertificate crossNamespaceAccountCertificate, + TestCertificate noWorkloadUriCertificate) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java index 5391da0e6c..1e22e86052 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -17,6 +17,7 @@ import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository.AssociationReceipt; @@ -44,7 +45,8 @@ class GameSessionTenantAssociationGrpcTest { repository, mock(PublishedReleaseBundleService.class), "test", - new tools.jackson.databind.ObjectMapper()); + new tools.jackson.databind.ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); @Test void exactGameSessionPeerPrecedesSyntaxAndOwnerReads() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index 504f1bf7a6..6718c6aa85 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -1,6 +1,11 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -12,6 +17,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Optional; @@ -21,8 +27,11 @@ import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; @@ -30,12 +39,15 @@ import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyRequest; import net.firedevops.firemud.gamedesign.v1.ResolvePublishedRealmEntryPolicyResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; +import org.jooq.exception.DataAccessException; import org.jooq.exception.TooManyRowsException; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -44,6 +56,223 @@ import tools.jackson.databind.ObjectMapper; class TenantIdentityGrpcServiceTest { + private static final String SOURCE_ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final String SOURCE_ACCOUNT_MIGRATOR_PEER = + "spiffe://firemud/ns/test/sa/account-tenant-migrator"; + private static final String SOURCE_GAME_SESSION_PEER = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String SOURCE_WRONG_NAMESPACE_GAME_SESSION_PEER = + "spiffe://firemud/ns/other/sa/game-session-service"; + private static final String SOURCE_WORLD_MANAGEMENT_PEER = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String SOURCE_WRONG_NAMESPACE_WORLD_MANAGEMENT_PEER = + "spiffe://firemud/ns/other/sa/world-management-service"; + private static final String SOURCE_GAME_DESIGN_PEER = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final UUID SOURCE_FRESH_CREATION_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_FRESH_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_RUNTIME_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID SOURCE_RUNTIME_TENANT_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private final GameAuthoredWorldSourceRepository authoredWorldRepository = + mock(GameAuthoredWorldSourceRepository.class); + + @Test + void authoredSourceReadRejectsUnrelatedOrWrongNamespacePeersBeforeOwnerAccess() { + assertThat(GrpcPeerIdentity.parseUri(SOURCE_ACCOUNT_MIGRATOR_PEER)).isEmpty(); + for (String peer : + new String[] { + null, + SOURCE_ACCOUNT_PEER, + SOURCE_ACCOUNT_MIGRATOR_PEER, + SOURCE_WRONG_NAMESPACE_GAME_SESSION_PEER, + SOURCE_WRONG_NAMESPACE_WORLD_MANAGEMENT_PEER, + SOURCE_GAME_DESIGN_PEER + }) { + AuthoredSourceObserver observer = authoredSourceCall(authoredSourceRequest(), peer); + assertEquals(Status.Code.PERMISSION_DENIED, observer.errorCode); + assertNull(observer.value); + assertFalse(observer.completed); + } + AuthoredSourceObserver malformedRequestWithWrongPeer = + authoredSourceCall( + authoredSourceRequest().toBuilder().setRequestId("malformed").build(), + SOURCE_GAME_DESIGN_PEER); + assertEquals(Status.Code.PERMISSION_DENIED, malformedRequestWithWrongPeer.errorCode); + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void authoredSourceReadAllowsExactSameNamespaceWorldManagementPeer() { + AuthoredWorldSourceEvidence evidence = authoredSourceEvidence("test"); + when(authoredWorldRepository.read( + SOURCE_FRESH_OPERATION_ID, SOURCE_RUNTIME_TENANT_ID, "world-one", "test")) + .thenReturn(Optional.of(evidence)); + + AuthoredSourceObserver observer = + authoredSourceCall(authoredSourceRequest(), SOURCE_WORLD_MANAGEMENT_PEER); + + assertNull(observer.errorCode); + assertTrue(observer.completed); + assertNotNull(observer.value); + assertEquals(SOURCE_RUNTIME_REQUEST_ID.toString(), observer.value.getRequestId()); + assertEquals(evidence.evidenceDigest(), observer.value.getEvidenceDigest()); + verify(authoredWorldRepository) + .read(SOURCE_FRESH_OPERATION_ID, SOURCE_RUNTIME_TENANT_ID, "world-one", "test"); + } + + @Test + void authoredSourceRejectsMalformedTupleAndUnknownFieldsBeforeRead() { + ResolveAuthoredWorldSourceRequest exact = authoredSourceRequest(); + for (ResolveAuthoredWorldSourceRequest request : + new ResolveAuthoredWorldSourceRequest[] { + exact.toBuilder().setOperationId("19").build(), + exact.toBuilder().setCanonicalTenantId("00000000-0000-0000-0000-000000000000").build(), + exact.toBuilder().setRequestId("1-1-1-1-1").build(), + exact.toBuilder().setWorldSlug(" World").build(), + exact.toBuilder().setWorldSlug("w".repeat(121)).build(), + exact.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build() + }) { + AuthoredSourceObserver observer = authoredSourceCall(request, SOURCE_GAME_SESSION_PEER); + assertEquals(Status.Code.INVALID_ARGUMENT, observer.errorCode); + assertNull(observer.value); + } + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void authoredSourceEchoesDistinctReadIdentityAndCompleteImmutableReceipt() { + AuthoredWorldSourceEvidence evidence = authoredSourceEvidence("test"); + when(authoredWorldRepository.read( + SOURCE_FRESH_OPERATION_ID, SOURCE_RUNTIME_TENANT_ID, "world-one", "test")) + .thenReturn(Optional.of(evidence)); + AuthoredSourceObserver first = + authoredSourceCall(authoredSourceRequest(), SOURCE_GAME_SESSION_PEER); + AuthoredSourceObserver retry = + authoredSourceCall(authoredSourceRequest(), SOURCE_GAME_SESSION_PEER); + assertNull(first.errorCode); + assertTrue(first.completed); + assertEquals(first.value, retry.value); + assertEquals(SOURCE_RUNTIME_REQUEST_ID.toString(), first.value.getRequestId()); + assertEquals( + SOURCE_FRESH_CREATION_REQUEST_ID.toString(), first.value.getRegistrationRequestId()); + assertEquals(evidence.evidenceDigest(), first.value.getEvidenceDigest()); + assertEquals("tenant-one", first.value.getTenantSlug()); + assertEquals("world-one", first.value.getWorldSlug()); + assertEquals("Wörld", first.value.getWorldDisplayName()); + assertEquals(19L, first.value.getSourceGameRowId()); + verifyNoInteractions(repository, associationRepository); + } + + @Test + void authoredSourceReadDoesNotReturnAbsentChangedOrUnavailableEvidence() { + when(authoredWorldRepository.read( + SOURCE_FRESH_OPERATION_ID, SOURCE_RUNTIME_TENANT_ID, "world-one", "test")) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(authoredSourceEvidence("other"))) + .thenThrow(new IllegalStateException("contradictory source")) + .thenThrow(new DataAccessException("db", new SQLException("offline", "08006"))); + for (Status.Code expected : + new Status.Code[] { + Status.Code.NOT_FOUND, Status.Code.FAILED_PRECONDITION, + Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE + }) { + AuthoredSourceObserver observer = + authoredSourceCall(authoredSourceRequest(), SOURCE_GAME_SESSION_PEER); + assertEquals(expected, observer.errorCode); + assertNull(observer.value); + assertFalse(observer.completed); + } + } + + private static ResolveAuthoredWorldSourceRequest authoredSourceRequest() { + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(SOURCE_RUNTIME_REQUEST_ID.toString()) + .setOperationId(SOURCE_FRESH_OPERATION_ID.toString()) + .setCanonicalTenantId(SOURCE_RUNTIME_TENANT_ID.toString()) + .setWorldSlug("world-one") + .build(); + } + + private static AuthoredWorldSourceEvidence authoredSourceEvidence(String namespace) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + SOURCE_FRESH_CREATION_REQUEST_ID, + SOURCE_RUNTIME_TENANT_ID, + "tenant-one", + "world-one", + "Wörld"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + SOURCE_FRESH_CREATION_REQUEST_ID, + SOURCE_FRESH_OPERATION_ID, + requestDigest, + SOURCE_RUNTIME_TENANT_ID, + "tenant-one", + "world-one", + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + SOURCE_FRESH_CREATION_REQUEST_ID, + SOURCE_FRESH_OPERATION_ID, + requestDigest, + SOURCE_RUNTIME_TENANT_ID, + "tenant-one", + "world-one", + "Wörld", + 19L, + "source-key", + "NEW_GAME_ROW", + evidenceDigest); + } + + private AuthoredSourceObserver authoredSourceCall( + ResolveAuthoredWorldSourceRequest request, String peer) { + AuthoredSourceObserver observer = new AuthoredSourceObserver(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + peer == null ? null : GrpcPeerIdentity.parseUri(peer).orElse(null)) + .run(() -> service.resolveAuthoredWorldSource(request, observer)); + return observer; + } + + private static final class AuthoredSourceObserver + implements StreamObserver { + private ResolveAuthoredWorldSourceResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final UUID TENANT_ID = UUID.fromString("87426bb3-a733-43f0-9c8e-2e379cbdf7ec"); private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -60,7 +289,8 @@ class TenantIdentityGrpcServiceTest { associationRepository, publishedReleaseBundleService, "test", - new ObjectMapper()); + new ObjectMapper(), + authoredWorldRepository); @Test void resolvesExactOwnerIdentityForAuthenticatedGameSessionPeer() { @@ -117,7 +347,8 @@ void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { associationRepository, publishedReleaseBundleService, "", - new ObjectMapper()); + new ObjectMapper(), + authoredWorldRepository); TestObserver observer = new TestObserver(); GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_URI).orElseThrow(); @@ -599,7 +830,8 @@ class FreshCreation { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "test", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); @Test void returnsExactImmutableReceiptOnlyToSameNamespaceAccountPeer() { @@ -676,7 +908,8 @@ void deniesMissingWrongServiceWrongNamespaceAndUnconfiguredPeerBeforeRead() { mock(GameSessionTenantAssociationRepository.class), mock(PublishedReleaseBundleService.class), "", - new ObjectMapper()); + new ObjectMapper(), + mock(GameAuthoredWorldSourceRepository.class)); Observer observer = new Observer(); GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); Context.current() diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index d6bd731255..ddfaf38592 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -13,5 +13,8 @@ firemudJooq { } dependencies { + testImplementation(libs.bouncycastle.pkix) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) implementation(project(":common-security")) } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfiguration.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfiguration.java new file mode 100644 index 0000000000..a671dd6b77 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfiguration.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.transaction.PlatformTransactionManager; + +/** Opt-in composition of World's durable authenticated authored-source owner boundary. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.authored-world-source", + name = "enabled", + havingValue = "true") +public class WorldAuthoredSourceIntakeConfiguration { + private static final String SERVER_CERTIFICATE = + "spring.ssl.bundle.pem.firemud-grpc.keystore.certificate"; + private static final String SERVER_PRIVATE_KEY = + "spring.ssl.bundle.pem.firemud-grpc.keystore.private-key"; + private static final String SERVER_CA_CERTIFICATE = + "spring.ssl.bundle.pem.firemud-grpc.truststore.certificate"; + + @Bean(initMethod = "init", destroyMethod = "close") + public AuthoredWorldSourceClient authoredWorldSourceClient( + Environment environment, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + requireSecureServer(environment); + return new AuthoredWorldSourceClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + public WorldAuthoredSourceIntakeService worldAuthoredSourceIntakeService( + AuthoredWorldSourceClient sourceClient, + WorldAuthoredSourceIntakeRepository repository, + PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new WorldAuthoredSourceIntakeService( + sourceClient, repository, transactionManager, workloadNamespace); + } + + static void requireSecureServer(Environment environment) { + if (!environment.getProperty("spring.grpc.server.enabled", Boolean.class, true) + || !environment.getProperty("spring.grpc.server.ssl.enabled", Boolean.class, true) + || !"REQUIRE" + .equalsIgnoreCase( + environment.getProperty("spring.grpc.server.ssl.client-auth", "REQUIRE"))) { + throw new IllegalStateException( + "World authored-source intake requires an enabled gRPC mTLS server " + + "with client-auth=REQUIRE"); + } + requireReadableFile(environment.getProperty(SERVER_CERTIFICATE), "server certificate"); + requireReadableFile(environment.getProperty(SERVER_PRIVATE_KEY), "server private key"); + requireReadableFile(environment.getProperty(SERVER_CA_CERTIFICATE), "server CA certificate"); + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.startsWith("classpath:")) { + throw new IllegalStateException( + "World authored-source intake requires file-backed server mTLS " + label); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "World authored-source intake requires file-backed server mTLS " + label, exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalStateException( + "World authored-source intake requires a readable file-backed server mTLS " + label); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java new file mode 100644 index 0000000000..6b40dbf5ed --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Versioned World-owned request and receipt digests for fresh authored-source intake. */ +public final class WorldAuthoredSourceIntakeDigest { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldAuthoredSourceIntakeDigest() {} + + public static String requestDigest( + String targetNamespace, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireNonNil(intakeRequestId, "intakeRequestId"); + requireFreshSource(targetNamespace, source); + return digest( + "world-authored-source-intake-request/v1", + targetNamespace, + intakeRequestId.toString(), + source.canonicalTenantId().toString(), + source.worldSlug(), + source.operationId().toString(), + source.evidenceDigest()); + } + + public static String receiptDigest( + String targetNamespace, + UUID operationId, + String requestDigest, + AuthoredWorldSourceEvidence source, + long localTenantKey) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + requireFreshSource(targetNamespace, source); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("localTenantKey must be positive"); + } + return digest( + "world-authored-source-intake-receipt/v1", + targetNamespace, + operationId.toString(), + requestDigest, + source.canonicalTenantId().toString(), + source.worldSlug(), + source.operationId().toString(), + source.evidenceDigest(), + Long.toString(localTenantKey)); + } + + static void requireFreshSource(String targetNamespace, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(source, "source"); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException( + "Fresh World authored-source intake requires NEW_GAME_ROW provenance"); + } + if (!targetNamespace.equals(source.targetNamespace())) { + throw new IllegalArgumentException("Source namespace differs from the intake namespace"); + } + AuthoredWorldSourceDigest.validateReadSelector( + targetNamespace, source.canonicalTenantId(), source.worldSlug()); + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + } + + private static String digest(String... segments) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java new file mode 100644 index 0000000000..1ed97bd246 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java @@ -0,0 +1,265 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.grpc.server.service.GrpcService; + +/** + * Opt-in gRPC adapter for authenticated authored-source intake and exact receipt readback. World + * binds the trusted namespace locally, and each method independently requires the exact same- + * namespace Game Design mTLS peer. + */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.authored-world-source", + name = "enabled", + havingValue = "true") +public final class WorldAuthoredSourceIntakeGrpcService + extends WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceImplBase { + private final WorldAuthoredSourceIntakeService intakeService; + private final String trustedNamespace; + + public WorldAuthoredSourceIntakeGrpcService( + WorldAuthoredSourceIntakeService intakeService, + @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + this.intakeService = Objects.requireNonNull(intakeService, "intakeService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) { + return; + } + IntakeRequest binding; + try { + binding = WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(binding.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + WorldAuthoredSourceIntakeReceipt receipt; + try { + receipt = + intakeService.intake( + binding.schemaVersion(), + binding.targetNamespace(), + binding.intakeRequestId(), + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + + IntakeAuthoredWorldSourceResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(binding, toCommittedReceipt(receipt)); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + public void readAuthoredWorldSourceIntake( + ReadAuthoredWorldSourceIntakeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) { + return; + } + ReadRequest readRequest; + try { + readRequest = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.binding().targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + Optional stored; + try { + IntakeRequest binding = readRequest.binding(); + stored = + intakeService.readCommittedReceipt( + binding.schemaVersion(), + binding.targetNamespace(), + readRequest.requestId(), + binding.intakeRequestId(), + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No committed World intake matches the exact request") + .asRuntimeException()); + return; + } + + ReadAuthoredWorldSourceIntakeResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse( + readRequest, toCommittedReceipt(stored.orElseThrow())); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static CommittedReceipt toCommittedReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + if (receipt == null) { + throw new IllegalArgumentException("World owner returned no committed intake receipt"); + } + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-design-service") + && peer.isInNamespace(trustedNamespace)) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Design workload is required") + .asRuntimeException()); + return false; + } + + private static void respondWithOwnerFailure( + StreamObserver responseObserver, RuntimeException exception) { + if (exception instanceof StatusRuntimeException statusException) { + responseObserver.onError(statusException); + } else if (exception instanceof SecurityException) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Design workload is required") + .asRuntimeException()); + } else if (exception + instanceof WorldAuthoredSourceIntakeRepository.RegistrationConflictException + || exception + instanceof WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World authored-source intake conflicts with committed evidence") + .asRuntimeException()); + } else if (exception instanceof IllegalArgumentException) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake binding is required") + .asRuntimeException()); + } else if (exception instanceof DataAccessResourceFailureException + || exception instanceof TransientDataAccessException) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake is temporarily unavailable") + .asRuntimeException()); + } else if (exception instanceof DataAccessException) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription("World intake storage could not complete the request") + .asRuntimeException()); + } else if (exception instanceof IllegalStateException) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World intake is unavailable in the current transaction state") + .asRuntimeException()); + } else { + responseObserver.onError( + Status.INTERNAL + .withDescription("World authored-source intake failed") + .asRuntimeException()); + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java new file mode 100644 index 0000000000..b25bbf5c34 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Complete immutable World-owned receipt for one fresh Game Design source intake. */ +public record WorldAuthoredSourceIntakeReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest, + long localTenantKey, + AuthoredWorldSourceEvidence source) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldAuthoredSourceIntakeReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source receipt version"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(sourceOperationId, "sourceOperationId"); + Objects.requireNonNull(sourceEvidenceDigest, "sourceEvidenceDigest"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(source, "source"); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("localTenantKey must be positive"); + } + WorldAuthoredSourceIntakeDigest.requireFreshSource(targetNamespace, source); + if (!targetNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !sourceEvidenceDigest.equals(source.evidenceDigest()) + || !requestDigest.equals( + WorldAuthoredSourceIntakeDigest.requestDigest(targetNamespace, intakeRequestId, source)) + || !receiptDigest.equals( + WorldAuthoredSourceIntakeDigest.receiptDigest( + targetNamespace, operationId, requestDigest, source, localTenantKey))) { + throw new IllegalArgumentException("World authored-source receipt fields or digests differ"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java new file mode 100644 index 0000000000..74b775e393 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java @@ -0,0 +1,629 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * World-owned immutable copy of authenticated, fresh Game Design authored-world source evidence. + */ +@Repository +public class WorldAuthoredSourceIntakeRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Table TENANT_ASSOCIATION = + DSL.table(DSL.name("world_authored_source_tenant_association")); + private static final Table TENANT_KEY_RESERVATION = + DSL.table(DSL.name("world_authored_source_tenant_key_reservation")); + private static final Table INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field RESERVED_TENANT_KEY = + DSL.field(DSL.name("tenant_key"), Long.class); + private static final Field RESERVATION_CLAIM_KIND = + DSL.field(DSL.name("claim_kind"), String.class); + private static final Field RESERVATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field RESERVATION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field STORED_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Short.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Short.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private static final String LOCK_LEGACY_TENANT_TABLES = + "LOCK TABLE generation_rule, instance, region, region_instance, room, room_exit, " + + "room_instance, room_instance_exit, world_design_aggregate_epoch, " + + "world_design_revision_ledger, world_design_scope_epoch, " + + "world_entity_spawn_binding, world_event, world_instance, zone, zone_instance " + + "IN SHARE MODE"; + private static final String MAX_OCCUPIED_TENANT_KEY = + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance UNION ALL " + + "SELECT tenant_key FROM world_authored_source_tenant_key_reservation UNION ALL " + + "SELECT local_tenant_key FROM world_authored_source_tenant_association" + + ") AS occupied_tenant_keys"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal Spring collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Retains the complete fresh Game Design receipt and its World-local tenant association. + * + *

The caller must already have authenticated Game Design and opened the World owner + * transaction. This method does not accept a forwarded digest in place of source evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredSourceIntakeReceipt acceptFresh( + String namespace, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireActiveOwnerTransaction(); + requireWritableReadCommittedOwnerTransaction(); + AuthoredWorldSourceEvidence validatedSource = validateFreshSource(namespace, source); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(namespace, intakeRequestId, validatedSource); + + Record priorRequest = findByRequest(namespace, intakeRequestId); + if (priorRequest != null) { + return requireExactReplay(priorRequest, intakeRequestId, requestDigest, validatedSource); + } + + lockFreshIntakeAndExistingTenantRows(); + + priorRequest = findByRequest(namespace, intakeRequestId); + if (priorRequest != null) { + return requireExactReplay(priorRequest, intakeRequestId, requestDigest, validatedSource); + } + requireUnclaimedSourceAndWorld(namespace, validatedSource); + + long localTenantKey = ensureTenantAssociation(validatedSource); + UUID operationId = UUID.randomUUID(); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + namespace, operationId, requestDigest, validatedSource, localTenantKey); + + int inserted = + dsl.insertInto(INTAKE) + .set(OPERATION_ID, operationId) + .set(STORED_SCHEMA_VERSION, (short) SCHEMA_VERSION) + .set(TARGET_NAMESPACE, namespace) + .set(INTAKE_REQUEST_ID, intakeRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(LOCAL_TENANT_KEY, localTenantKey) + .set(SOURCE_SCHEMA_VERSION, (short) validatedSource.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, validatedSource.registrationRequestId()) + .set(SOURCE_OPERATION_ID, validatedSource.operationId()) + .set(SOURCE_REQUEST_DIGEST, validatedSource.requestDigest()) + .set(CANONICAL_TENANT_ID, validatedSource.canonicalTenantId()) + .set(TENANT_SLUG, validatedSource.tenantSlug()) + .set(WORLD_SLUG, validatedSource.worldSlug()) + .set(WORLD_DISPLAY_NAME, validatedSource.worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, validatedSource.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, validatedSource.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, validatedSource.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, validatedSource.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .execute(); + if (inserted != 1) { + throw new RegistrationConflictException("World authored-source intake was not inserted"); + } + + Record persisted = findByRequest(namespace, intakeRequestId); + if (persisted == null) { + throw new InvalidIntakeEvidenceException( + "World authored-source intake disappeared before owner readback"); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(persisted); + requireExactReceipt(receipt, intakeRequestId, requestDigest, validatedSource); + requireTenantAssociation(receipt); + return receipt; + } + + /** Reads a committed World intake by its exact namespace and stable request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake read requires a committed-outcome owner read"); + } + return readValidated(namespace, intakeRequestId); + } + + private Optional readValidated( + String namespace, UUID intakeRequestId) { + validateReadKey(namespace, intakeRequestId); + Record record = findByRequest(namespace, intakeRequestId); + if (record == null) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireTenantAssociation(receipt); + return Optional.of(receipt); + } + + /** Reads a committed World intake by its exact canonical source-owned binding. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readBySource( + String namespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake read requires a committed-outcome owner read"); + } + validateSourceReadKey( + namespace, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + Record record = + dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(SOURCE_OPERATION_ID.eq(sourceOperationId)) + .and(SOURCE_EVIDENCE_DIGEST.eq(sourceEvidenceDigest))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireTenantAssociation(receipt); + return Optional.of(receipt); + } + + private void lockFreshIntakeAndExistingTenantRows() { + // Serialize allocator owners, then keep every current tenant-bearing table stable while the + // candidate is checked. Legacy writers do not take this association lock; their database + // reservation trigger rejects selectors already claimed by a canonical source. + dsl.execute("LOCK TABLE world_authored_source_tenant_association IN SHARE ROW EXCLUSIVE MODE"); + dsl.execute(LOCK_LEGACY_TENANT_TABLES); + } + + private void requireUnclaimedSourceAndWorld( + String namespace, AuthoredWorldSourceEvidence source) { + if (findBySourceOperation(namespace, source.operationId()) != null) { + throw new RegistrationConflictException( + "Game Design source operation is already claimed by another World intake"); + } + if (findBySourceRegistrationRequest(namespace, source.registrationRequestId()) != null) { + throw new RegistrationConflictException( + "Game Design source registration request is already claimed by another World intake"); + } + if (findByWorldSelector(namespace, source.canonicalTenantId(), source.worldSlug()) != null) { + throw new RegistrationConflictException( + "World selector is already associated with different source evidence"); + } + } + + private long ensureTenantAssociation(AuthoredWorldSourceEvidence source) { + Record existing = findTenantAssociation(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingTenantAssociation(existing, source); + long existingKey = Objects.requireNonNull(existing.get(LOCAL_TENANT_KEY, Long.class)); + requireCanonicalTenantKeyReservation(source, existingKey); + return existingKey; + } + + if (findTenantSlugAssociation(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already associated with another canonical tenant"); + } + if (findSourceRowAssociation(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already associated with another canonical tenant"); + } + + long localTenantKey = nextUnclaimedTenantKey(); + int inserted = + dsl.insertInto(TENANT_ASSOCIATION) + .set(TARGET_NAMESPACE, source.targetNamespace()) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(TENANT_SLUG, source.tenantSlug()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(LOCAL_TENANT_KEY, localTenantKey) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + requireCanonicalTenantKeyReservation(source, localTenantKey); + return localTenantKey; + } + + existing = findTenantAssociation(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingTenantAssociation(existing, source); + long existingKey = Objects.requireNonNull(existing.get(LOCAL_TENANT_KEY, Long.class)); + requireCanonicalTenantKeyReservation(source, existingKey); + return existingKey; + } + if (findTenantSlugAssociation(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already associated with another canonical tenant"); + } + if (findSourceRowAssociation(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already associated with another canonical tenant"); + } + throw new RegistrationConflictException( + "World authored-source tenant association conflicts with an owner claim"); + } + + private long nextUnclaimedTenantKey() { + Record allocation = dsl.fetchOne(MAX_OCCUPIED_TENANT_KEY); + if (allocation == null) { + throw new IllegalStateException("World tenant-selector allocation aggregate returned no row"); + } + Long maxKey = allocation.get(0, Long.class); + if (maxKey == null) { + throw new IllegalStateException("World tenant-selector allocation aggregate returned null"); + } + long currentMax = maxKey; + if (currentMax == Long.MAX_VALUE) { + throw new IllegalStateException("World has no remaining positive local tenant selectors"); + } + return Math.max(currentMax, 0L) + 1L; + } + + private void requireCanonicalTenantKeyReservation( + AuthoredWorldSourceEvidence source, long localTenantKey) { + dsl.insertInto(TENANT_KEY_RESERVATION) + .set(RESERVED_TENANT_KEY, localTenantKey) + .set(RESERVATION_CLAIM_KIND, "CANONICAL_AUTHORED_SOURCE") + .set(RESERVATION_NAMESPACE, source.targetNamespace()) + .set(RESERVATION_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .onConflictDoNothing() + .execute(); + Record reservation = findTenantKeyReservation(localTenantKey); + if (reservation == null + || !Objects.equals( + reservation.get(RESERVATION_CLAIM_KIND, String.class), "CANONICAL_AUTHORED_SOURCE") + || !Objects.equals( + reservation.get(RESERVATION_NAMESPACE, String.class), source.targetNamespace()) + || !Objects.equals( + reservation.get(RESERVATION_CANONICAL_TENANT_ID, UUID.class), + source.canonicalTenantId())) { + throw new RegistrationConflictException( + "World local tenant selector is already reserved by another claim"); + } + } + + private void requireTenantAssociation(WorldAuthoredSourceIntakeReceipt receipt) { + Record association = + findTenantAssociation(receipt.targetNamespace(), receipt.canonicalTenantId()); + if (association == null) { + throw new InvalidIntakeEvidenceException( + "World authored-source tenant association is missing"); + } + requireMatchingTenantAssociation(association, receipt.source()); + if (!Objects.equals(association.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey())) { + throw new InvalidIntakeEvidenceException( + "World authored-source private tenant selector differs from its association"); + } + Record reservation = findTenantKeyReservation(receipt.localTenantKey()); + if (reservation == null + || !Objects.equals( + reservation.get(RESERVATION_CLAIM_KIND, String.class), "CANONICAL_AUTHORED_SOURCE") + || !Objects.equals( + reservation.get(RESERVATION_NAMESPACE, String.class), receipt.targetNamespace()) + || !Objects.equals( + reservation.get(RESERVATION_CANONICAL_TENANT_ID, UUID.class), + receipt.canonicalTenantId())) { + throw new InvalidIntakeEvidenceException( + "World authored-source private tenant selector reservation is missing or changed"); + } + } + + private Record findTenantKeyReservation(long tenantKey) { + return dsl.selectFrom(TENANT_KEY_RESERVATION) + .where(RESERVED_TENANT_KEY.eq(tenantKey)) + .fetchOne(); + } + + private void requireMatchingTenantAssociation( + Record association, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(association.get(TARGET_NAMESPACE, String.class), source.targetNamespace()) + || !Objects.equals( + association.get(CANONICAL_TENANT_ID, UUID.class), source.canonicalTenantId()) + || !Objects.equals(association.get(TENANT_SLUG, String.class), source.tenantSlug()) + || !Objects.equals( + association.get(SOURCE_GAME_ROW_ID, Long.class), source.sourceGameRowId()) + || !Objects.equals( + association.get(SOURCE_GAME_TENANT_KEY, String.class), source.sourceGameTenantKey()) + || !Objects.equals( + association.get(SOURCE_PROVENANCE_KIND, String.class), source.provenanceKind())) { + throw new RegistrationConflictException( + "Canonical tenant source or stable tenant selector conflicts with its World association"); + } + } + + private WorldAuthoredSourceIntakeReceipt requireExactReplay( + Record record, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireExactReceipt(receipt, intakeRequestId, requestDigest, source); + requireTenantAssociation(receipt); + return receipt; + } + + private void requireExactReceipt( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.requestDigest().equals(requestDigest) + || !receipt.source().equals(source)) { + throw new RegistrationConflictException( + "World intake request identity was reused with changed scope or source evidence"); + } + } + + private AuthoredWorldSourceEvidence validateFreshSource( + String namespace, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(namespace, "namespace"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new InvalidIntakeEvidenceException( + "World authored-source target namespace must be one canonical DNS label"); + } + Objects.requireNonNull(source, "source"); + try { + AuthoredWorldSourceEvidence validated = + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + WorldAuthoredSourceIntakeDigest.requireFreshSource(namespace, validated); + return validated; + } catch (IllegalArgumentException exception) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source evidence is invalid or not fresh", exception); + } + } + + private void validateReadKey(String namespace, UUID intakeRequestId) { + if (namespace == null || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("namespace must be one canonical DNS label"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + } + + private void validateSourceReadKey( + String namespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (!GameTenantCreationDigest.isDigest(sourceEvidenceDigest)) { + throw new IllegalArgumentException( + "sourceEvidenceDigest must be a canonical lowercase SHA-256 digest"); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake requires an active World owner transaction"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World authored-source intake requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World authored-source intake requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World authored-source intake requires a writable READ COMMITTED owner transaction"); + } + } + + private Record findByRequest(String namespace, UUID intakeRequestId) { + return dsl.selectFrom(INTAKE) + .where(TARGET_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + } + + private Record findBySourceOperation(String namespace, UUID sourceOperationId) { + return dsl.selectFrom(INTAKE) + .where(TARGET_NAMESPACE.eq(namespace).and(SOURCE_OPERATION_ID.eq(sourceOperationId))) + .fetchOne(); + } + + private Record findBySourceRegistrationRequest(String namespace, UUID sourceRequestId) { + return dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE.eq(namespace).and(SOURCE_REGISTRATION_REQUEST_ID.eq(sourceRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector(String namespace, UUID tenantId, String worldSlug) { + return dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private Record findTenantAssociation(String namespace, UUID canonicalTenantId) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + } + + private Record findTenantSlugAssociation(String namespace, String tenantSlug) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + } + + private Record findSourceRowAssociation(String namespace, long sourceGameRowId) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(SOURCE_GAME_ROW_ID.eq(sourceGameRowId))) + .fetchOne(); + } + + private WorldAuthoredSourceIntakeReceipt toReceipt(Record record) { + try { + Short schemaVersion = Objects.requireNonNull(record.get(STORED_SCHEMA_VERSION, Short.class)); + Short sourceSchemaVersion = + Objects.requireNonNull(record.get(SOURCE_SCHEMA_VERSION, Short.class)); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + sourceSchemaVersion.intValue(), + Objects.requireNonNull(record.get(TARGET_NAMESPACE, String.class)), + Objects.requireNonNull(record.get(SOURCE_REGISTRATION_REQUEST_ID, UUID.class)), + Objects.requireNonNull(record.get(SOURCE_OPERATION_ID, UUID.class)), + Objects.requireNonNull(record.get(SOURCE_REQUEST_DIGEST, String.class)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID, UUID.class)), + Objects.requireNonNull(record.get(TENANT_SLUG, String.class)), + Objects.requireNonNull(record.get(WORLD_SLUG, String.class)), + Objects.requireNonNull(record.get(WORLD_DISPLAY_NAME, String.class)), + Objects.requireNonNull(record.get(SOURCE_GAME_ROW_ID, Long.class)), + Objects.requireNonNull(record.get(SOURCE_GAME_TENANT_KEY, String.class)), + Objects.requireNonNull(record.get(SOURCE_PROVENANCE_KIND, String.class)), + Objects.requireNonNull(record.get(SOURCE_EVIDENCE_DIGEST, String.class))); + if (schemaVersion.intValue() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported local intake schema version"); + } + return new WorldAuthoredSourceIntakeReceipt( + schemaVersion.intValue(), + Objects.requireNonNull(record.get(TARGET_NAMESPACE, String.class)), + Objects.requireNonNull(record.get(INTAKE_REQUEST_ID, UUID.class)), + Objects.requireNonNull(record.get(OPERATION_ID, UUID.class)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID, UUID.class)), + Objects.requireNonNull(record.get(WORLD_SLUG, String.class)), + source.operationId(), + source.evidenceDigest(), + Objects.requireNonNull(record.get(REQUEST_DIGEST, String.class)), + Objects.requireNonNull(record.get(RECEIPT_DIGEST, String.class)), + Objects.requireNonNull(record.get(LOCAL_TENANT_KEY, Long.class)), + source); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIntakeEvidenceException) { + throw exception; + } + throw new InvalidIntakeEvidenceException( + "Persisted World authored-source intake evidence is invalid", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIntakeEvidenceException extends IllegalStateException { + public InvalidIntakeEvidenceException(String message) { + super(message); + } + + public InvalidIntakeEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java new file mode 100644 index 0000000000..d32ecac3a6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -0,0 +1,336 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired World owner intake. A fresh, authenticated Game Design source read precedes the local + * transaction that retains its complete evidence and private tenant association. + */ +public class WorldAuthoredSourceIntakeService { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AuthoredWorldSourceClient sourceClient; + private final WorldAuthoredSourceIntakeRepository repository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner configuration is validated before use; no resources or finalizer are " + + "acquired.") + public WorldAuthoredSourceIntakeService( + AuthoredWorldSourceClient sourceClient, + WorldAuthoredSourceIntakeRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Retains one fresh source binding. The intake request identity is stable across exact retries; + * each first attempt gets a separate Game Design read identity. + */ + public WorldAuthoredSourceIntakeReceipt intake( + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + return intake( + SCHEMA_VERSION, + workloadNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + } + + /** Accepts the complete wire binding after authenticating the exact Game Design workload. */ + public WorldAuthoredSourceIntakeReceipt intake( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireAuthenticatedGameDesignCaller(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + validateRequest( + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + + Optional prior = + repository.read(workloadNamespace, intakeRequestId); + if (prior.isPresent()) { + return requireReceiptForRequest( + prior.get(), + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + } + + AuthoredWorldSourceEvidence source = + sourceClient.read( + new ReadRequest( + workloadNamespace, + newReadRequestId(intakeRequestId), + sourceOperationId, + canonicalTenantId, + worldSlug)); + requireFreshSourceForRequest( + source, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest); + + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, intakeRequestId, source)); + if (accepted == null) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World owner transaction returned no authored-source receipt"); + } + requireReceiptForRequest( + accepted, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + source); + + Optional committed = + repository.read(workloadNamespace, intakeRequestId); + if (committed.isEmpty()) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source intake is missing after commit readback"); + } + WorldAuthoredSourceIntakeReceipt readback = committed.get(); + requireReceiptForRequest( + readback, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + source); + if (!accepted.equals(readback)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source intake changed during commit readback"); + } + return readback; + } + + /** Reads only an exact committed receipt; it never re-reads Game Design or allocates state. */ + public Optional readCommittedReceipt( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireAuthenticatedGameDesignCaller(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + requireNonNil(requestId, "requestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + if (requestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + validateRequest( + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + + Optional receipt = + repository.read(targetNamespace, intakeRequestId); + if (receipt.isEmpty()) { + return Optional.empty(); + } + return Optional.of( + requireReceiptForRequest( + receipt.orElseThrow(), + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest)); + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World authored-source intake requires the authenticated Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake cannot enter from an ambient transaction"); + } + } + + private void validateSchemaAndNamespace(int schemaVersion, String targetNamespace) { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + if (!workloadNamespace.equals(targetNamespace)) { + throw new SecurityException( + "World authored-source intake target namespace does not match this workload"); + } + } + + private void validateRequest( + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { + throw new IllegalArgumentException( + "expectedSourceEvidenceDigest must be a canonical SHA-256 digest"); + } + } + + private void requireFreshSourceForRequest( + AuthoredWorldSourceEvidence source, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + if (source == null + || !workloadNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !expectedSourceEvidenceDigest.equals(source.evidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source does not match the requested World intake"); + } + try { + WorldAuthoredSourceIntakeDigest.requireFreshSource(workloadNamespace, source); + } catch (IllegalArgumentException exception) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source is invalid or not fresh", exception); + } + } + + private WorldAuthoredSourceIntakeReceipt requireReceiptForRequest( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + return requireReceiptForRequest( + receipt, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + null); + } + + private WorldAuthoredSourceIntakeReceipt requireReceiptForRequest( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + AuthoredWorldSourceEvidence expectedSource) { + if (receipt == null + || !workloadNamespace.equals(receipt.targetNamespace()) + || !intakeRequestId.equals(receipt.intakeRequestId()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug()) + || !sourceOperationId.equals(receipt.sourceOperationId()) + || !expectedSourceEvidenceDigest.equals(receipt.sourceEvidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.RegistrationConflictException( + "World intake request identity was reused with changed scope or source evidence"); + } + + AuthoredWorldSourceEvidence source = receipt.source(); + if (expectedSource != null && !expectedSource.equals(source)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source receipt does not retain the complete source evidence"); + } + requireFreshSourceForRequest( + source, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(workloadNamespace, intakeRequestId, source); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + workloadNamespace, + receipt.operationId(), + requestDigest, + source, + receipt.localTenantKey()); + if (!requestDigest.equals(receipt.requestDigest()) + || !receiptDigest.equals(receipt.receiptDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source receipt digest readback is invalid"); + } + return receipt; + } + + private static UUID newReadRequestId(UUID intakeRequestId) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (NIL_UUID.equals(readRequestId) || intakeRequestId.equals(readRequestId)); + return readRequestId; + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index db840be505..b04227ba2a 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -87,6 +87,9 @@ firemud: grpc: public-methods: - world_management.v1.WorldManagementService/Ping + # JWT bypass is exact-method only; the adapter requires the same-namespace Game Design mTLS peer. + - world_management.v1.WorldAuthoredSourceIntakeService/IntakeAuthoredWorldSource + - world_management.v1.WorldAuthoredSourceIntakeService/ReadAuthoredWorldSourceIntake grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql b/services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql new file mode 100644 index 0000000000..8e586e23ea --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql @@ -0,0 +1,250 @@ +CREATE TABLE world_authored_source_tenant_association ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + CONSTRAINT pk_world_authored_source_tenant_association + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_world_authored_source_tenant_local_key UNIQUE (local_tenant_key), + CONSTRAINT uq_world_authored_source_tenant_selector UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_world_authored_source_game_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_world_authored_source_tenant_binding + UNIQUE (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_tenant_canonical_id + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_world_authored_source_tenant_game_row CHECK (source_game_row_id > 0), + CONSTRAINT ck_world_authored_source_tenant_local_key CHECK (local_tenant_key > 0), + CONSTRAINT ck_world_authored_source_tenant_provenance + CHECK (source_provenance_kind = 'NEW_GAME_ROW') +); + +CREATE TABLE world_authored_source_tenant_key_reservation ( + tenant_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + target_namespace VARCHAR(63), + canonical_tenant_id UUID, + CONSTRAINT pk_world_authored_source_tenant_key_reservation PRIMARY KEY (tenant_key), + CONSTRAINT fk_world_authored_source_tenant_key_canonical_binding + FOREIGN KEY (target_namespace, canonical_tenant_id, tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_tenant_key_claim_kind CHECK ( + (claim_kind = 'LEGACY_NUMERIC' + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL) + OR + (claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND tenant_key > 0) + ) +); + +INSERT INTO world_authored_source_tenant_key_reservation (tenant_key, claim_kind) +SELECT DISTINCT tenant_id, 'LEGACY_NUMERIC' +FROM ( + SELECT tenant_id FROM generation_rule + UNION ALL SELECT tenant_id FROM instance + UNION ALL SELECT tenant_id FROM region + UNION ALL SELECT tenant_id FROM region_instance + UNION ALL SELECT tenant_id FROM room + UNION ALL SELECT tenant_id FROM room_exit + UNION ALL SELECT tenant_id FROM room_instance + UNION ALL SELECT tenant_id FROM room_instance_exit + UNION ALL SELECT tenant_id FROM world_design_aggregate_epoch + UNION ALL SELECT tenant_id FROM world_design_revision_ledger + UNION ALL SELECT tenant_id FROM world_design_scope_epoch + UNION ALL SELECT tenant_id FROM world_entity_spawn_binding + UNION ALL SELECT tenant_id FROM world_event + UNION ALL SELECT tenant_id FROM world_instance + UNION ALL SELECT tenant_id FROM zone + UNION ALL SELECT tenant_id FROM zone_instance +) AS existing_world_tenant_keys; + +-- [jooq ignore start] +CREATE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_key BIGINT; +BEGIN + INSERT INTO world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE + SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_reject_authored_source_history_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World authored-source association and receipt history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE FUNCTION world_protect_tenant_key_reservation_history() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.tenant_key IS NOT DISTINCT FROM NEW.tenant_key + AND OLD.claim_kind IS NOT DISTINCT FROM NEW.claim_kind + AND OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + THEN + RETURN NEW; + END IF; + END IF; + RAISE EXCEPTION 'World tenant-key reservation history cannot be changed or deleted' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_tenant_key_reservation_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_tenant_key_reservation + FOR EACH ROW EXECUTE FUNCTION world_protect_tenant_key_reservation_history(); + +CREATE TRIGGER trg_world_tenant_key_reservation_no_truncate + BEFORE TRUNCATE ON world_authored_source_tenant_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_association_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_tenant_association + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_association_no_truncate + BEFORE TRUNCATE ON world_authored_source_tenant_association + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_reserve_generation_rule_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_region_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON region + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_region_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON region_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_exit_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_instance_exit_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_instance_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_aggregate_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_revision_ledger + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_scope_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_event_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_event + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_zone_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON zone + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_zone_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON zone_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +-- [jooq ignore stop] + +CREATE TABLE world_authored_source_intake ( + operation_id UUID NOT NULL, + schema_version SMALLINT NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + local_tenant_key BIGINT NOT NULL, + source_schema_version SMALLINT NOT NULL, + source_registration_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + CONSTRAINT pk_world_authored_source_intake PRIMARY KEY (operation_id), + CONSTRAINT uq_world_authored_source_intake_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_world_authored_source_intake_source_operation + UNIQUE (target_namespace, source_operation_id), + CONSTRAINT uq_world_authored_source_intake_source_request + UNIQUE (target_namespace, source_registration_request_id), + CONSTRAINT uq_world_authored_source_intake_world + UNIQUE (target_namespace, canonical_tenant_id, world_slug), + CONSTRAINT fk_world_authored_source_intake_tenant_binding + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_intake_schema CHECK (schema_version = 1), + CONSTRAINT ck_world_authored_source_intake_source_schema CHECK (source_schema_version = 1), + CONSTRAINT ck_world_authored_source_intake_local_key CHECK (local_tenant_key > 0), + CONSTRAINT ck_world_authored_source_intake_source_game_row CHECK (source_game_row_id > 0), + CONSTRAINT ck_world_authored_source_intake_provenance + CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + CONSTRAINT ck_world_authored_source_intake_request_digest + CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_source_request_digest + CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_source_evidence_digest + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_receipt_digest + CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_non_nil_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ) +); + +-- [jooq ignore start] +CREATE TRIGGER trg_world_authored_source_intake_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_intake + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_intake_no_truncate + BEFORE TRUNCATE ON world_authored_source_intake + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql b/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql new file mode 100644 index 0000000000..56b19ac59d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql @@ -0,0 +1,219 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_key BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' AND EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + + INSERT INTO world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE + SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_reject_tenant_table_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION + 'World tenant-bearing tables require owner-qualified row mutation; TRUNCATE is forbidden' + USING ERRCODE = '23514'; +END; +$$; + +DROP TRIGGER trg_reserve_generation_rule_tenant_key ON generation_rule; +CREATE TRIGGER trg_reserve_generation_rule_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_instance_tenant_key ON instance; +CREATE TRIGGER trg_reserve_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_region_tenant_key ON region; +CREATE TRIGGER trg_reserve_region_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON region + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_region_instance_tenant_key ON region_instance; +CREATE TRIGGER trg_reserve_region_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON region_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_tenant_key ON room; +CREATE TRIGGER trg_reserve_room_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_exit_tenant_key ON room_exit; +CREATE TRIGGER trg_reserve_room_exit_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_instance_tenant_key ON room_instance; +CREATE TRIGGER trg_reserve_room_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_instance_exit_tenant_key ON room_instance_exit; +CREATE TRIGGER trg_reserve_room_instance_exit_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_instance_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + ON world_design_aggregate_epoch; +CREATE TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_aggregate_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + ON world_design_revision_ledger; +CREATE TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_revision_ledger + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + ON world_design_scope_epoch; +CREATE TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_scope_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + ON world_entity_spawn_binding; +CREATE TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_event_tenant_key ON world_event; +CREATE TRIGGER trg_reserve_world_event_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_event + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_instance_tenant_key ON world_instance; +CREATE TRIGGER trg_reserve_world_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_zone_tenant_key ON zone; +CREATE TRIGGER trg_reserve_zone_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON zone + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_zone_instance_tenant_key ON zone_instance; +CREATE TRIGGER trg_reserve_zone_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON zone_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +CREATE TRIGGER trg_generation_rule_no_truncate + BEFORE TRUNCATE ON generation_rule + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_instance_no_truncate + BEFORE TRUNCATE ON instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_region_no_truncate + BEFORE TRUNCATE ON region + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_region_instance_no_truncate + BEFORE TRUNCATE ON region_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_no_truncate + BEFORE TRUNCATE ON room + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_exit_no_truncate + BEFORE TRUNCATE ON room_exit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_instance_no_truncate + BEFORE TRUNCATE ON room_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_instance_exit_no_truncate + BEFORE TRUNCATE ON room_instance_exit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_aggregate_epoch_no_truncate + BEFORE TRUNCATE ON world_design_aggregate_epoch + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_revision_ledger_no_truncate + BEFORE TRUNCATE ON world_design_revision_ledger + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_scope_epoch_no_truncate + BEFORE TRUNCATE ON world_design_scope_epoch + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_entity_spawn_binding_no_truncate + BEFORE TRUNCATE ON world_entity_spawn_binding + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_event_no_truncate + BEFORE TRUNCATE ON world_event + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_instance_no_truncate + BEFORE TRUNCATE ON world_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_zone_no_truncate + BEFORE TRUNCATE ON zone + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_zone_instance_no_truncate + BEFORE TRUNCATE ON zone_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java new file mode 100644 index 0000000000..d764f18544 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -0,0 +1,1329 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredSourceIntakeIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Set PROTECTED_TENANT_TABLES = + Set.of( + "generation_rule", + "instance", + "region", + "region_instance", + "room", + "room_exit", + "room_instance", + "room_instance_exit", + "world_design_aggregate_epoch", + "world_design_revision_ledger", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "world_event", + "world_instance", + "zone", + "zone_instance"); + private static final String OCCUPIED_LEGACY_KEYS = + "SELECT COUNT(*) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance" + + ") AS occupied_world_keys WHERE occupied_key = ?"; + private static final String MAX_OCCUPIED_TENANT_KEY = + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance UNION ALL " + + "SELECT tenant_key FROM world_authored_source_tenant_key_reservation UNION ALL " + + "SELECT local_tenant_key FROM world_authored_source_tenant_association" + + ") AS occupied_tenant_keys"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private WorldAuthoredSourceIntakeRepository repository; + @Autowired private Flyway flyway; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { + assertThat(Arrays.stream(flyway.info().applied()).map(MigrationInfo::getScript).toList()) + .containsSubsequence( + "V23__initial_admission_bind_hold.sql", "V23.1__world_authored_source_intake.sql"); + long existingLegacyTenantKey = + 8_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + Long legacyRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + existingLegacyTenantKey, + "retained-world-allocation-guard"), + "retained region insert did not return its row") + .get(0, Long.class); + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + existingLegacyTenantKey, + "same-legacy-selector-remains-valid"); + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", existingLegacyTenantKey, legacyRegionId); + + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = tenantSlug(canonicalTenantId); + long sourceRowId = sourceRowId(canonicalTenantId); + AuthoredWorldSourceEvidence firstSource = + source(canonicalTenantId, tenantSlug, "violet-wilds", sourceRowId, "Café 🐉"); + UUID firstRequestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt first = accept(firstRequestId, firstSource); + + assertThat(first.source()).isEqualTo(firstSource); + assertThat(first.localTenantKey()).isGreaterThan(existingLegacyTenantKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne(OCCUPIED_LEGACY_KEYS, first.localTenantKey()), + "legacy key occupancy query returned no row") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ? AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' " + + "AND target_namespace = ? AND canonical_tenant_id = ?", + first.localTenantKey(), + NAMESPACE, + canonicalTenantId), + "canonical tenant-key reservation count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(read(firstRequestId)).contains(first); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + first.localTenantKey(), + "cannot-claim-canonical-selector")) + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertReservedCanonicalSelectorRejected); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", + first.localTenantKey(), + legacyRegionId)) + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertReservedCanonicalSelectorRejected); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT tenant_id FROM region WHERE id = ?", legacyRegionId), + "retained region tenant readback returned no row") + .get(0, Long.class)) + .isEqualTo(existingLegacyTenantKey); + + AuthoredWorldSourceEvidence secondSource = + source(canonicalTenantId, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); + WorldAuthoredSourceIntakeReceipt second = accept(UUID.randomUUID(), secondSource); + + assertThat(second.localTenantKey()).isEqualTo(first.localTenantKey()); + assertThat(second.source().tenantSlug()).isEqualTo(first.source().tenantSlug()); + assertThat(second.source().sourceGameRowId()).isEqualTo(first.source().sourceGameRowId()); + assertThat(second.source().sourceGameTenantKey()) + .isEqualTo(first.source().sourceGameTenantKey()); + assertThat(second.source().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + } + + @Test + void readBySourceReturnsExactCommittedReceiptOnRepeatedCallsWithoutGrowth() { + UUID tenant = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source(tenant, tenantSlug(tenant), "source-read-world", sourceRowId(tenant), "Source Read"); + WorldAuthoredSourceIntakeReceipt receipt = accept(UUID.randomUUID(), source); + long intakeCount = countRows("world_authored_source_intake"); + long associationCount = countRows("world_authored_source_tenant_association"); + long reservationCount = countRows("world_authored_source_tenant_key_reservation"); + + assertThat( + repository.readBySource( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(receipt); + assertThat( + repository.readBySource( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(receipt); + assertThat(countRows("world_authored_source_intake")).isEqualTo(intakeCount); + assertThat(countRows("world_authored_source_tenant_association")).isEqualTo(associationCount); + assertThat(countRows("world_authored_source_tenant_key_reservation")) + .isEqualTo(reservationCount); + } + + @Test + void readBySourceRejectsAnyChangedBindingAndRetainedOrUnmappedEvidence() { + UUID tenant = UUID.randomUUID(); + String tenantSlug = tenantSlug(tenant); + long sourceRowId = sourceRowId(tenant); + AuthoredWorldSourceEvidence source = + source(tenant, tenantSlug, "source-binding-world", sourceRowId, "Source Binding"); + accept(UUID.randomUUID(), source); + + assertThat( + repository.readBySource( + "other-namespace", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + UUID.randomUUID(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, tenant, "another-world", source.operationId(), source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), UUID.randomUUID(), source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + "sha256:" + "0".repeat(64))) + .isEmpty(); + + AuthoredWorldSourceEvidence retainedSource = + source(tenant, tenantSlug, "retained-world", sourceRowId, "Retained", "RETAINED_GAME_V30"); + assertThat( + repository.readBySource( + NAMESPACE, + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.operationId(), + retainedSource.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + UUID.randomUUID(), + "unmapped-world", + UUID.randomUUID(), + source.evidenceDigest())) + .isEmpty(); + } + + @Test + void readBySourceRejectsMalformedBinding() { + UUID tenant = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, tenantSlug(tenant), "malformed-read-world", sourceRowId(tenant), "Malformed"); + UUID nilUuid = new UUID(0L, 0L); + + assertThatThrownBy( + () -> + repository.readBySource( + "FireMud", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, + nilUuid, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, + tenant, + "Malformed-World", + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), nilUuid, source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), source.operationId(), "sha256:BAD")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void readBySourceDoesNotExposeUncommittedOwnerEvidence() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "uncommitted-read-world", + sourceRowId(tenant), + "Uncommitted"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + transactionTemplate.execute( + status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + return null; + }); + + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(repository.read(NAMESPACE, requestId).orElseThrow()); + } + + @Test + void deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims() { + UUID tenant = UUID.randomUUID(); + String tenantSlug = tenantSlug(tenant); + long sourceRowId = sourceRowId(tenant); + AuthoredWorldSourceEvidence firstSource = + source(tenant, tenantSlug, "violet-wilds", sourceRowId, "Violet Wilds"); + UUID requestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt first = accept(requestId, firstSource); + + AuthoredWorldSourceEvidence changedRequestSource = + source(tenant, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); + assertThatThrownBy(() -> accept(requestId, changedRequestSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + accept( + requestId, + source( + UUID.randomUUID(), + "unrelated-tenant-selector", + "violet-wilds", + 7_456_321_987L, + "Violet Wilds"))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + AuthoredWorldSourceEvidence changedWorldSource = + source(tenant, tenantSlug, "violet-wilds", sourceRowId, "Changed Display"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), changedWorldSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy(() -> accept(UUID.randomUUID(), firstSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + AuthoredWorldSourceEvidence changedTenantSource = + source( + tenant, + "renamed-" + tenant.toString().replace("-", ""), + "new-world", + sourceRowId, + "New World"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), changedTenantSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + UUID retainedTenantId = UUID.randomUUID(); + AuthoredWorldSourceEvidence retainedSource = + source( + retainedTenantId, + tenantSlug(retainedTenantId), + "retained-world", + sourceRowId(retainedTenantId), + "Retained", + "RETAINED_GAME_V30"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), retainedSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + assertThat(read(requestId)).contains(first); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + } + + @Test + void ownerTransactionRollbackLeavesNeitherAssociationNorReceipt() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "rolled-back-world", + sourceRowId(tenant), + "Rolled Back World"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transactionTemplate.execute( + status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + throw new ForcedOwnerRollbackException(); + })) + .isInstanceOf(ForcedOwnerRollbackException.class); + + assertThat(read(requestId)).isEmpty(); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + } + + @Test + void rejectsImmutableHistoryMutationAndTruncation() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, tenantSlug(tenant), "immutable-world", sourceRowId(tenant), "Immutable World"); + WorldAuthoredSourceIntakeReceipt receipt = accept(requestId, source); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_intake SET world_display_name = ? " + + "WHERE operation_id = ?", + "substituted", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_source_intake CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_tenant_association SET tenant_slug = ? " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + "changed-selector", + NAMESPACE, + tenant)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenant)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE world_authored_source_tenant_association CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_tenant_key_reservation " + + "SET claim_kind = 'LEGACY_NUMERIC' WHERE tenant_key = ?", + receipt.localTenantKey())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?", + receipt.localTenantKey())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE world_authored_source_tenant_key_reservation CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThat(read(requestId)).contains(receipt); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(countReservationsForCanonicalTenant(tenant)).isEqualTo(1L); + } + + @Test + void canonicalReservationsGuardEveryWorldRowMutationTrigger() throws SQLException { + String schema = "world_canonical_guard_" + UUID.randomUUID().toString().replace("-", ""); + UUID canonicalTenantId = UUID.randomUUID(); + long canonicalTenantKey = + 80_000_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + long legacyTenantKey = canonicalTenantKey + 1L; + + try { + migrateFixture(schema, MigrationVersion.fromVersion("23.1")); + long canonicalRegionId = + seedCanonicalRegionBeforeGuard(schema, canonicalTenantId, canonicalTenantKey); + migrateFixture(schema, MigrationVersion.fromVersion("24")); + + try (Connection connection = fixtureConnection(schema)) { + assertProtectedReservationTriggerCatalog(connection); + assertProtectedTenantTruncateTriggerCatalog(connection); + + for (String table : PROTECTED_TENANT_TABLES) { + assertSqlState("23514", () -> insertTenantKeyRow(connection, table, canonicalTenantKey)); + long expectedRows = table.equals("region") ? 1L : 0L; + assertThat(countRowsForTenant(connection, table, canonicalTenantKey)) + .as("canonical-key insert side effects for %s", table) + .isEqualTo(expectedRows); + } + + long legacyRegionId = insertRegion(connection, legacyTenantKey, "legacy-before-update"); + assertSqlState( + "23514", + () -> + updateRegion( + connection, + canonicalRegionId, + legacyTenantKey, + "attempted move from canonical key")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(countRowsForTenant(connection, "region", legacyTenantKey)).isEqualTo(1L); + assertThat(readReservationClaimKind(connection, legacyTenantKey)) + .isEqualTo("LEGACY_NUMERIC"); + + assertSqlState( + "23514", + () -> updateRegionPayload(connection, canonicalRegionId, "attempted payload update")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + + assertSqlState("23514", () -> deleteRegion(connection, canonicalRegionId)); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(readReservationClaimKind(connection, canonicalTenantKey)) + .isEqualTo("CANONICAL_AUTHORED_SOURCE"); + + updateRegionPayload(connection, legacyRegionId, "legacy payload update remains allowed"); + assertThat(readRegionName(connection, legacyRegionId)) + .isEqualTo("legacy payload update remains allowed"); + deleteRegion(connection, legacyRegionId); + assertThat(countRowsForTenant(connection, "region", legacyTenantKey)).isZero(); + assertThat(readReservationClaimKind(connection, legacyTenantKey)) + .isEqualTo("LEGACY_NUMERIC"); + + assertSqlState("23514", () -> truncateTenantTable(connection, "region")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(countRowsForTenant(connection, "region", canonicalTenantKey)).isEqualTo(1L); + assertThat(readReservationClaimKind(connection, canonicalTenantKey)) + .isEqualTo("CANONICAL_AUTHORED_SOURCE"); + assertThat(countCanonicalAssociations(connection, canonicalTenantId)).isEqualTo(1L); + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "unsupported-transaction-world", + sourceRowId(tenant), + "Unsupported Transaction World"); + + TransactionTemplate readOnly = new TransactionTemplate(transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> repository.acceptFresh(NAMESPACE, requestId, source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + + TransactionTemplate repeatableRead = new TransactionTemplate(transactionManager); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableRead.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + + assertThatThrownBy(() -> repository.acceptFresh(NAMESPACE, requestId, source)) + .isInstanceOf(IllegalTransactionStateException.class); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + } + + @Test + void concurrentExactRetriesReturnTheSingleCommittedReceipt() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-world", + sourceRowId(tenant), + "Concurrent World"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> acceptWhenReleased(transactionTemplate, ready, start, requestId, source)); + Future second = + executor.submit( + () -> acceptWhenReleased(transactionTemplate, ready, start, requestId, source)); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + WorldAuthoredSourceIntakeReceipt firstReceipt = first.get(20, TimeUnit.SECONDS); + WorldAuthoredSourceIntakeReceipt secondReceipt = second.get(20, TimeUnit.SECONDS); + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(read(requestId)).contains(firstReceipt); + } + } + + @Test + void concurrentLegacyNumericClaimSerializesBeforeFreshSelectorAllocation() throws Exception { + long legacyTenantKey = 6_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-numeric-allocation-world", + sourceRowId(tenant), + "Concurrent Numeric Allocation World"); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + CountDownLatch legacyInserted = new CountDownLatch(1); + CountDownLatch allowLegacyCommit = new CountDownLatch(1); + CountDownLatch intakeStarted = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future legacyWrite = + executor.submit( + () -> + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + legacyTenantKey, + "concurrent-legacy-selector"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); + assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); + + Future intake = + executor.submit( + () -> { + intakeStarted.countDown(); + return intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + }); + assertThat(intakeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitAllocatorLockWait(); + allowLegacyCommit.countDown(); + + legacyWrite.get(20, TimeUnit.SECONDS); + WorldAuthoredSourceIntakeReceipt receipt = intake.get(20, TimeUnit.SECONDS); + assertThat(receipt.localTenantKey()).isGreaterThan(legacyTenantKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM region WHERE tenant_id = ?", legacyTenantKey), + "legacy region count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ? AND claim_kind = 'LEGACY_NUMERIC'", + legacyTenantKey), + "legacy tenant-key reservation count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(read(requestId)).contains(receipt); + } + } + + @Test + void concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-reserved-selector-world", + sourceRowId(tenant), + "Concurrent Reserved Selector World"); + TransactionTemplate ownerTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + CountDownLatch intakePrepared = new CountDownLatch(1); + CountDownLatch allowIntakeCommit = new CountDownLatch(1); + AtomicReference preparedReceipt = new AtomicReference<>(); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future intake = + executor.submit( + () -> + ownerTransaction.execute( + status -> { + WorldAuthoredSourceIntakeReceipt receipt = + repository.acceptFresh(NAMESPACE, requestId, source); + preparedReceipt.set(receipt); + intakePrepared.countDown(); + await(allowIntakeCommit, 20); + return receipt; + })); + assertThat(intakePrepared.await(5, TimeUnit.SECONDS)).isTrue(); + WorldAuthoredSourceIntakeReceipt receipt = preparedReceipt.get(); + assertThat(receipt).isNotNull(); + + Future legacyWrite = + executor.submit( + () -> { + try { + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + receipt.localTenantKey(), + "cannot-race-private-selector"); + return null; + }); + return true; + } catch (DataIntegrityViolationException expectedReservedKeyRejection) { + assertReservedCanonicalSelectorRejected(expectedReservedKeyRejection); + return false; + } + }); + + awaitLegacyWriterLockWait(); + allowIntakeCommit.countDown(); + assertThat(intake.get(20, TimeUnit.SECONDS)).isEqualTo(receipt); + assertThat(legacyWrite.get(20, TimeUnit.SECONDS)).isFalse(); + assertThat(read(requestId)).contains(receipt); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM region WHERE tenant_id = ?", + receipt.localTenantKey()), + "canonical-selector region count query returned no row") + .get(0, Long.class)) + .isZero(); + } + } + + private static void migrateFixture(String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static long seedCanonicalRegionBeforeGuard( + String schema, UUID canonicalTenantId, long canonicalTenantKey) throws SQLException { + try (Connection connection = fixtureConnection(schema); + Statement controls = connection.createStatement()) { + // Test-only bypass in this isolated V23.1 schema; restore triggers before applying V24. + controls.execute("SET session_replication_role = replica"); + try { + String tenantSlug = tenantSlug(canonicalTenantId); + String sourceKey = "src-" + canonicalTenantId.toString().replace("-", ""); + try (PreparedStatement association = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_association " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, local_tenant_key) " + + "VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)")) { + association.setString(1, NAMESPACE); + association.setObject(2, canonicalTenantId); + association.setString(3, tenantSlug); + association.setLong(4, sourceRowId(canonicalTenantId)); + association.setString(5, sourceKey); + association.setLong(6, canonicalTenantKey); + association.executeUpdate(); + } + try (PreparedStatement reservation = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_key_reservation " + + "(tenant_key, claim_kind, target_namespace, canonical_tenant_id) " + + "VALUES (?, 'CANONICAL_AUTHORED_SOURCE', ?, ?)")) { + reservation.setLong(1, canonicalTenantKey); + reservation.setString(2, NAMESPACE); + reservation.setObject(3, canonicalTenantId); + reservation.executeUpdate(); + } + try (PreparedStatement region = + connection.prepareStatement( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id")) { + region.setLong(1, canonicalTenantKey); + region.setString(2, "test-only canonical row"); + try (ResultSet result = region.executeQuery()) { + if (!result.next()) { + throw new SQLException("Test-only canonical region seed returned no row"); + } + return result.getLong(1); + } + } + } finally { + controls.execute("SET session_replication_role = origin"); + } + } + } + + private static Connection fixtureConnection(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema(schema); + return connection; + } + + private static void dropFixtureSchema(String schema) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static void assertProtectedReservationTriggerCatalog(Connection connection) + throws SQLException { + Set actualTables = new HashSet<>(); + try (Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT table_row.relname, trigger_row.tgname, function_row.proname, " + + "trigger_row.tgtype, trigger_row.tgenabled " + + "FROM pg_trigger AS trigger_row " + + "JOIN pg_class AS table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace AS namespace_row " + + "ON namespace_row.oid = table_row.relnamespace " + + "JOIN pg_proc AS function_row ON function_row.oid = trigger_row.tgfoid " + + "WHERE namespace_row.nspname = current_schema() " + + "AND trigger_row.tgname LIKE 'trg_reserve_%_tenant_key' " + + "AND NOT trigger_row.tgisinternal")) { + while (result.next()) { + String table = result.getString(1); + actualTables.add(table); + assertThat(result.getString(2)).isEqualTo("trg_reserve_" + table + "_tenant_key"); + assertThat(result.getString(3)).isEqualTo("world_claim_legacy_numeric_tenant_key"); + assertThat(result.getInt(4)).isEqualTo(31); + assertThat(result.getString(5)).isEqualTo("O"); + } + } + assertThat(actualTables).containsExactlyInAnyOrderElementsOf(PROTECTED_TENANT_TABLES); + } + + private static void assertProtectedTenantTruncateTriggerCatalog(Connection connection) + throws SQLException { + Set actualTables = new HashSet<>(); + try (Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT table_row.relname, trigger_row.tgname, trigger_row.tgtype, " + + "trigger_row.tgenabled " + + "FROM pg_trigger AS trigger_row " + + "JOIN pg_class AS table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace AS namespace_row " + + "ON namespace_row.oid = table_row.relnamespace " + + "JOIN pg_proc AS function_row ON function_row.oid = trigger_row.tgfoid " + + "WHERE namespace_row.nspname = current_schema() " + + "AND function_row.proname = 'world_reject_tenant_table_truncate' " + + "AND NOT trigger_row.tgisinternal")) { + while (result.next()) { + String table = result.getString(1); + actualTables.add(table); + assertThat(result.getString(2)).isEqualTo("trg_" + table + "_no_truncate"); + assertThat(result.getInt(3)).isEqualTo(34); + assertThat(result.getString(4)).isEqualTo("O"); + } + } + assertThat(actualTables).containsExactlyInAnyOrderElementsOf(PROTECTED_TENANT_TABLES); + } + + private static void truncateTenantTable(Connection connection, String table) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("TRUNCATE " + table + " CASCADE"); + } + } + + private static void insertTenantKeyRow(Connection connection, String table, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("INSERT INTO " + table + " (tenant_id) VALUES (?)")) { + statement.setLong(1, tenantKey); + statement.executeUpdate(); + } + } + + private static long insertRegion(Connection connection, long tenantKey, String name) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id")) { + statement.setLong(1, tenantKey); + statement.setString(2, name); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + throw new SQLException("Region fixture insert returned no row"); + } + return result.getLong(1); + } + } + } + + private static void updateRegion( + Connection connection, long regionId, long tenantKey, String name) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("UPDATE region SET tenant_id = ?, name = ? WHERE id = ?")) { + statement.setLong(1, tenantKey); + statement.setString(2, name); + statement.setLong(3, regionId); + statement.executeUpdate(); + } + } + + private static void updateRegionPayload(Connection connection, long regionId, String name) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("UPDATE region SET name = ? WHERE id = ?")) { + statement.setString(1, name); + statement.setLong(2, regionId); + statement.executeUpdate(); + } + } + + private static void deleteRegion(Connection connection, long regionId) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("DELETE FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + statement.executeUpdate(); + } + } + + private static long countRowsForTenant(Connection connection, String table, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT COUNT(*) FROM " + table + " WHERE tenant_id = ?")) { + statement.setLong(1, tenantKey); + try (ResultSet result = statement.executeQuery()) { + result.next(); + return result.getLong(1); + } + } + } + + private static String readRegionName(Connection connection, long regionId) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT name FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + throw new SQLException("Expected region fixture row was missing"); + } + return result.getString(1); + } + } + } + + private static void assertCanonicalRegion( + Connection connection, long regionId, long tenantKey, String name) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT tenant_id, name FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(tenantKey); + assertThat(result.getString(2)).isEqualTo(name); + } + } + } + + private static String readReservationClaimKind(Connection connection, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT claim_kind FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?")) { + statement.setLong(1, tenantKey); + try (ResultSet result = statement.executeQuery()) { + return result.next() ? result.getString(1) : null; + } + } + } + + private static long countCanonicalAssociations(Connection connection, UUID canonicalTenantId) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?")) { + statement.setString(1, NAMESPACE); + statement.setObject(2, canonicalTenantId); + try (ResultSet result = statement.executeQuery()) { + result.next(); + return result.getLong(1); + } + } + } + + private static void assertSqlState(String expected, SqlAction action) throws SQLException { + SQLException rejected = null; + try { + action.execute(); + } catch (SQLException exception) { + rejected = exception; + } + if (rejected == null) { + throw new AssertionError("Expected PostgreSQL rejection with SQLSTATE " + expected); + } + assertThat(rejected.getSQLState()).isEqualTo(expected); + } + + @FunctionalInterface + private interface SqlAction { + void execute() throws SQLException; + } + + private WorldAuthoredSourceIntakeReceipt accept( + UUID requestId, AuthoredWorldSourceEvidence source) { + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + return transactionTemplate.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + } + + private WorldAuthoredSourceIntakeReceipt acceptWhenReleased( + TransactionTemplate transactionTemplate, + CountDownLatch ready, + CountDownLatch start, + UUID requestId, + AuthoredWorldSourceEvidence source) { + ready.countDown(); + await(start); + return transactionTemplate.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + } + + private java.util.Optional read(UUID requestId) { + return repository.read(NAMESPACE, requestId); + } + + private long countRows(String tableName) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) FROM " + tableName), + "table row count query returned no row") + .get(0, Long.class); + } + + private long countForCanonicalTenant(UUID tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_association WHERE " + + "target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId), + "canonical tenant association count query returned no row") + .get(0, Long.class); + } + + private void assertReservedCanonicalSelectorRejected(Throwable throwable) { + assertThat(throwable).hasStackTraceContaining("is reserved for a canonical authored source"); + + Throwable cause = throwable; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + } + + private long countReservationsForCanonicalTenant(UUID tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId), + "canonical tenant-key reservation count query returned no row") + .get(0, Long.class); + } + + private void awaitAllocatorLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + Long waiting = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' " + + "AND lower(query) LIKE 'lock table generation_rule%'"), + "allocator lock-wait query returned no row") + .get(0, Long.class); + if (waiting != null && waiting > 0L) { + return; + } + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL lock wait", exception); + } + } + throw new IllegalStateException( + "Fresh intake did not wait for the retained tenant-table writer"); + } + + private void awaitLegacyWriterLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + Long waiting = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' " + + "AND lower(query) LIKE 'insert into region%'"), + "legacy writer lock-wait query returned no row") + .get(0, Long.class); + if (waiting != null && waiting > 0L) { + return; + } + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL legacy-writer lock wait", exception); + } + } + throw new IllegalStateException( + "Legacy numeric writer did not wait for the fresh intake owner transaction"); + } + + private static final class ForcedOwnerRollbackException extends RuntimeException { + private ForcedOwnerRollbackException() { + super("Force the test owner transaction to roll back"); + } + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceRowId, String displayName) { + return source(tenantId, tenantSlug, worldSlug, sourceRowId, displayName, "NEW_GAME_ROW"); + } + + private static String tenantSlug(UUID tenantId) { + return "tenant-" + tenantId.toString().replace("-", ""); + } + + private static long sourceRowId(UUID tenantId) { + long positive = tenantId.getLeastSignificantBits() & Long.MAX_VALUE; + return positive == 0L ? 1L : positive; + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, + String tenantSlug, + String worldSlug, + long sourceRowId, + String displayName, + String provenance) { + UUID registrationId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String sourceGameTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private static void await(CountDownLatch latch) { + await(latch, 5); + } + + private static void await(CountDownLatch latch, long timeoutSeconds) { + try { + if (!latch.await(timeoutSeconds, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent intake test gate"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent intake test was interrupted", exception); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java new file mode 100644 index 0000000000..3804347c20 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -0,0 +1,661 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Message; +import io.grpc.ForwardingServerCall; +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 java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +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.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.jooq.DSLContext; +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.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL owner commit and exact receipt readback over the unregistered physical mTLS boundary. + * Game Design source evidence is synthetic; this does not exercise its producer or network. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredSourceIntakeMtlsIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final List WORLD_MUTATION_SNAPSHOT_TABLES = + List.of( + "region", + "zone", + "room", + "instance", + "room_exit", + "generation_rule", + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit", + "world_event", + "world_design_revision_ledger", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "initial_admission_bind_hold", + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake"); + private static final String WORLD_SERVER_URI = + "spiffe://firemud/ns/firemud/sa/world-management-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @TempDir Path tempDirectory; + + @Autowired private WorldAuthoredSourceIntakeRepository repository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.GameDesignClient gameDesignClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.GameSessionClient gameSessionClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.EntityManagementClient + entityManagementClient; + + private Server server; + private ConcurrentLinkedQueue wireResponses; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @BeforeAll + static void createFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=World Intake Integration Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_SERVER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/firemud/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/firemud/sa/account-service")); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void commitsFreshWorldOwnerReceiptThenReturnsExactReceiptOverAuthenticatedSocket() + throws Exception { + Scenario scenario = newScenario("violet-wilds"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + startReceiver(syntheticSource, new AtomicBoolean(false)); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-first")) { + CommittedReceipt intakeReceipt = client.intake(scenario.intakeRequest()); + WorldAuthoredSourceIntakeReceipt persisted = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + CommittedReceipt exactRead = client.read(scenario.readRequest()); + + assertThat(persisted.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(intakeReceipt).isEqualTo(publicReceipt(persisted)); + assertThat(exactRead).isEqualTo(intakeReceipt); + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())).contains(persisted); + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(1L, 1L, 1L)); + assertNoPrivateLocalTenantKeyOnWire(); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void reconcilesLostSuccessAcknowledgementWithExactRetryAndCommittedReadback() throws Exception { + Scenario scenario = newScenario("amber-coast"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + AtomicBoolean dropNextSuccess = new AtomicBoolean(true); + startReceiver(syntheticSource, dropNextSuccess); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-retry")) { + assertThatThrownBy(() -> client.intake(scenario.intakeRequest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + WorldAuthoredSourceIntakeReceipt committedAfterLostAck = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + DbCounts afterCommit = dbCounts(scenario); + assertThat(committedAfterLostAck.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(afterCommit).isEqualTo(new DbCounts(1L, 1L, 1L)); + assertThat(dropNextSuccess.get()).isFalse(); + + CommittedReceipt retryReceipt = client.intake(scenario.intakeRequest()); + CommittedReceipt readReceipt = client.read(scenario.readRequest()); + + assertThat(retryReceipt).isEqualTo(publicReceipt(committedAfterLostAck)); + assertThat(readReceipt).isEqualTo(publicReceipt(committedAfterLostAck)); + assertThat(retryReceipt.operationId()).isEqualTo(committedAfterLostAck.operationId()); + assertThat(retryReceipt.requestDigest()).isEqualTo(committedAfterLostAck.requestDigest()); + assertThat(retryReceipt.receiptDigest()).isEqualTo(committedAfterLostAck.receiptDigest()); + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())) + .contains(committedAfterLostAck); + assertThat(dbCounts(scenario)).isEqualTo(afterCommit); + assertNoPrivateLocalTenantKeyOnWire(); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation() throws Exception { + Scenario scenario = newScenario("silver-marsh"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + startReceiver(syntheticSource, new AtomicBoolean(false)); + + try (WorldAuthoredSourceIntakeClient wrongCaller = + intakeClient(pki.accountClient(), "account")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> wrongCaller.intake(scenario.intakeRequest())); + assertStatus(Status.Code.PERMISSION_DENIED, () -> wrongCaller.read(scenario.readRequest())); + } + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(0L, 0L, 0L)); + verifyNoInteractions(syntheticSource); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-scope")) { + CommittedReceipt accepted = client.intake(scenario.intakeRequest()); + WorldAuthoredSourceIntakeReceipt original = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + assertThat(client.read(scenario.readRequest())).isEqualTo(accepted); + + IntakeRequest changedIntake = + new IntakeRequest( + 1, + NAMESPACE, + scenario.intakeRequestId(), + scenario.canonicalTenantId(), + "changed-world-selector", + scenario.sourceOperationId(), + scenario.sourceEvidence().evidenceDigest()); + ReadRequest changedRead = new ReadRequest(changedIntake, UUID.randomUUID()); + + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.intake(changedIntake)); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.read(changedRead)); + + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())).contains(original); + assertThat(original.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(1L, 1L, 1L)); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + private AuthoredWorldSourceClient sourceBoundary(Scenario scenario) { + AuthoredWorldSourceClient syntheticSource = mock(AuthoredWorldSourceClient.class); + when(syntheticSource.read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class))) + .thenAnswer( + invocation -> { + AuthoredWorldSourceGrpcCodec.ReadRequest request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.operationId()).isEqualTo(scenario.sourceOperationId()); + assertThat(request.canonicalTenantId()).isEqualTo(scenario.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(scenario.worldSlug()); + AuthoredWorldSourceEvidence answer = scenario.sourceEvidence(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return answer; + }); + return syntheticSource; + } + + private void startReceiver( + AuthoredWorldSourceClient syntheticSource, AtomicBoolean dropNextSuccess) throws Exception { + WorldAuthoredSourceIntakeService owner = + new WorldAuthoredSourceIntakeService( + syntheticSource, repository, transactionManager, NAMESPACE); + WorldAuthoredSourceIntakeGrpcService handler = + new WorldAuthoredSourceIntakeGrpcService(owner, NAMESPACE); + wireResponses = new ConcurrentLinkedQueue<>(); + var withPeerIdentity = ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + var withResponseCapture = + ServerInterceptors.intercept( + withPeerIdentity, responseCaptureAndDrop(wireResponses, dropNextSuccess)); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServer().privateKey(), pki.worldServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(withResponseCapture) + .build() + .start(); + } + + private WorldAuthoredSourceIntakeClient intakeClient(TestCertificate certificate, String label) + throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + endpoints(), tlsProperties(certificate, label), new GrpcChannelFactory(), NAMESPACE); + client.init(); + return client; + } + + private ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = tempDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = tempDirectory.resolve(label + "-client.key"); + Path caCertificate = tempDirectory.resolve("test-ca.crt"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private static ServerInterceptor responseCaptureAndDrop( + ConcurrentLinkedQueue capturedResponses, AtomicBoolean dropNextSuccess) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean droppedResponse; + + @Override + public void sendMessage(RespT message) { + if (message instanceof Message protobufMessage) { + capturedResponses.add(protobufMessage); + } + if (message instanceof IntakeAuthoredWorldSourceResponse + && dropNextSuccess.compareAndSet(true, false)) { + droppedResponse = true; + return; + } + super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + if (droppedResponse && status.isOk()) { + super.close( + Status.UNAVAILABLE.withDescription( + "Test deliberately lost a committed intake acknowledgement"), + trailers); + return; + } + super.close(status, trailers); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + private void assertNoPrivateLocalTenantKeyOnWire() { + assertThat( + IntakeAuthoredWorldSourceResponse.getDescriptor().findFieldByName("local_tenant_key")) + .isNull(); + assertThat( + ReadAuthoredWorldSourceIntakeResponse.getDescriptor() + .findFieldByName("local_tenant_key")) + .isNull(); + assertThat(wireResponses).isNotEmpty(); + for (Message response : wireResponses) { + assertThat(response.getDescriptorForType().findFieldByName("local_tenant_key")).isNull(); + assertThat(response.getUnknownFields().asMap()).isEmpty(); + assertThat(response.getAllFields().keySet()) + .noneMatch(field -> field.getName().equals("local_tenant_key")); + } + } + + private DbCounts dbCounts(Scenario scenario) { + return new DbCounts( + count( + "SELECT COUNT(*) FROM world_authored_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + scenario.intakeRequestId()), + count( + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + scenario.canonicalTenantId()), + count( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND claim_kind = 'CANONICAL_AUTHORED_SOURCE'", + NAMESPACE, + scenario.canonicalTenantId())); + } + + private Map> worldMutationRowSnapshot() { + Map> snapshot = new LinkedHashMap<>(); + for (String table : WORLD_MUTATION_SNAPSHOT_TABLES) { + snapshot.put( + table, + dsl.fetch("SELECT to_jsonb(world_row)::text FROM " + table + " AS world_row ORDER BY 1") + .getValues(0, String.class)); + } + return snapshot; + } + + private long count(String query, Object... bindings) { + return Objects.requireNonNull( + dsl.fetchOne(query, bindings), "World intake count query returned no row") + .get(0, Long.class); + } + + private static CommittedReceipt publicReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private static Scenario newScenario(String worldSlug) { + UUID tenantId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID registrationRequestId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenantId.toString().replace("-", "").substring(0, 12); + String displayName = "World " + worldSlug; + long sourceGameRowId = + Math.abs(UUID.randomUUID().getMostSignificantBits() % 1_000_000_000L) + 1L; + String sourceGameTenantKey = "src-" + UUID.randomUUID().toString().replace("-", ""); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + return new Scenario( + tenantId, intakeRequestId, sourceOperationId, UUID.randomUUID(), worldSlug, evidence); + } + + private static void assertStatus(Status.Code expected, ThrowingAction action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static String pem(String type, byte[] bytes) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record Scenario( + UUID canonicalTenantId, + UUID intakeRequestId, + UUID sourceOperationId, + UUID readRequestId, + String worldSlug, + AuthoredWorldSourceEvidence sourceEvidence) { + IntakeRequest intakeRequest() { + return new IntakeRequest( + 1, + NAMESPACE, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidence.evidenceDigest()); + } + + ReadRequest readRequest() { + return new ReadRequest(intakeRequest(), readRequestId); + } + } + + private record DbCounts(long receipts, long associations, long reservations) {} + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient) {} + + @FunctionalInterface + private interface ThrowingAction { + void run() throws Throwable; + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfigurationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfigurationTest.java new file mode 100644 index 0000000000..e0971f8b65 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeConfigurationTest.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import javax.net.ssl.SSLException; +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.tenant.AuthoredWorldSourceClient; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.transaction.PlatformTransactionManager; + +class WorldAuthoredSourceIntakeConfigurationTest { + private static final String NAMESPACE = "authored-source-world-test"; + private static final String SERVER_CERTIFICATE = + "spring.ssl.bundle.pem.firemud-grpc.keystore.certificate"; + private static final String SERVER_PRIVATE_KEY = + "spring.ssl.bundle.pem.firemud-grpc.keystore.private-key"; + private static final String SERVER_CA_CERTIFICATE = + "spring.ssl.bundle.pem.firemud-grpc.truststore.certificate"; + + @TempDir Path temporaryDirectory; + + @Test + void missingFeatureFlagDoesNotRegisterClientOwnerOrGrpcReceiver() { + new ApplicationContextRunner() + .withUserConfiguration( + WorldAuthoredSourceIntakeConfiguration.class, + WorldAuthoredSourceIntakeGrpcService.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AuthoredWorldSourceClient.class); + assertThat(context).doesNotHaveBean(WorldAuthoredSourceIntakeService.class); + assertThat(context).doesNotHaveBean(WorldAuthoredSourceIntakeGrpcService.class); + }); + new ApplicationContextRunner() + .withUserConfiguration( + WorldAuthoredSourceIntakeConfiguration.class, + WorldAuthoredSourceIntakeGrpcService.class) + .withPropertyValues("firemud.authored-world-source.enabled=false") + .run( + context -> + assertThat(context).doesNotHaveBean(WorldAuthoredSourceIntakeGrpcService.class)); + } + + @Test + void explicitEnableRegistersOnlyWithFileBackedMutualTlsAndTrustedNamespace() throws IOException { + Material material = material(); + secureRunner(material, NAMESPACE) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(AuthoredWorldSourceClient.class); + assertThat(context).hasSingleBean(WorldAuthoredSourceIntakeService.class); + assertThat(context).hasSingleBean(WorldAuthoredSourceIntakeGrpcService.class); + }); + } + + @Test + void explicitEnableFailsClosedForMissingIdentityOrInsecureServerOrClient() throws IOException { + Material material = material(); + secureRunner(material, "").run(context -> assertThat(context).hasFailed()); + secureRunner(material, NAMESPACE) + .withPropertyValues("spring.grpc.server.ssl.enabled=false") + .run(context -> assertThat(context).hasFailed()); + secureRunner(material, NAMESPACE) + .withPropertyValues("spring.grpc.server.ssl.client-auth=NONE") + .run(context -> assertThat(context).hasFailed()); + secureRunner(material, NAMESPACE, true).run(context -> assertThat(context).hasFailed()); + secureRunner(material, NAMESPACE) + .withPropertyValues(SERVER_CERTIFICATE + "=classpath:server.crt") + .run(context -> assertThat(context).hasFailed()); + } + + private ApplicationContextRunner secureRunner(Material material, String workloadNamespace) { + return secureRunner(material, workloadNamespace, false); + } + + private ApplicationContextRunner secureRunner( + Material material, String workloadNamespace, boolean plaintext) { + return new ApplicationContextRunner() + .withUserConfiguration( + WorldAuthoredSourceIntakeConfiguration.class, + WorldAuthoredSourceIntakeGrpcService.class) + .withBean( + WorldAuthoredSourceIntakeRepository.class, + () -> mock(WorldAuthoredSourceIntakeRepository.class)) + .withBean(PlatformTransactionManager.class, () -> mock(PlatformTransactionManager.class)) + .withBean(ServiceEndpointsProperties.class, ServiceEndpointsProperties::new) + .withBean(CommonGrpcClientProperties.class, () -> material.clientProperties(plaintext)) + .withBean( + GrpcChannelFactory.class, WorldAuthoredSourceIntakeConfigurationTest::channelFactory) + .withPropertyValues( + "firemud.authored-world-source.enabled=true", + "firemud.grpc.workload-namespace=" + workloadNamespace, + "spring.grpc.server.enabled=true", + "spring.grpc.server.ssl.enabled=true", + "spring.grpc.server.ssl.client-auth=REQUIRE", + SERVER_CERTIFICATE + "=" + material.serverCertificate(), + SERVER_PRIVATE_KEY + "=" + material.serverPrivateKey(), + SERVER_CA_CERTIFICATE + "=" + material.serverCaCertificate()); + } + + private Material material() throws IOException { + return new Material( + file("client.crt"), + file("client.key"), + file("client-ca.crt"), + file("server.crt"), + file("server.key"), + file("server-ca.crt")); + } + + private Path file(String name) throws IOException { + return Files.writeString(temporaryDirectory.resolve(name), "test tls material"); + } + + private static GrpcChannelFactory channelFactory() { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + try { + when(factory.buildChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean())) + .thenReturn(mock(ManagedChannel.class)); + } catch (SSLException exception) { + throw new IllegalStateException("Unable to configure test gRPC channel", exception); + } + return factory; + } + + private record Material( + Path clientCertificate, + Path clientPrivateKey, + Path clientCaCertificate, + Path serverCertificate, + Path serverPrivateKey, + Path serverCaCertificate) { + CommonGrpcClientProperties clientProperties(boolean plaintext) { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(clientCaCertificate.toString()); + properties.setPlaintext(plaintext); + return properties; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java new file mode 100644 index 0000000000..3231c170f7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java @@ -0,0 +1,131 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeDigestTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + + @Test + void emitsSharedUnicodeAndFramingVectorsForCompleteSourceAndPrivateAssociation() { + AuthoredWorldSourceEvidence source = source("violet-wilds", "Café 🐉", "NEW_GAME_ROW"); + + assertThat(source.requestDigest()) + .isEqualTo("sha256:2f2e50fd98aede5418d7b52b8c837e12b092edd4044624b4047d21123cb35ba3"); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:0084bd312cf3c13540d453c6a1e173b6b8ef5436a57a55db3363e2cd6879cbda"); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + assertThat(requestDigest) + .isEqualTo("sha256:1946ce9cb46af17732c4ec06445d7d9e297ac9bc22e30e7dde2858f9e1626c1f"); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, requestDigest, source, 9001L)) + .isEqualTo("sha256:7d0ab0104385d80e5a2bc1f72386ca09b50473d262a0389840a90136a4778fb7"); + } + + @Test + void requestAndReceiptDigestsBindEveryLocalScopeAndAllocationInput() { + AuthoredWorldSourceEvidence source = source("violet-wilds", "Café 🐉", "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence changedWorld = source("amber-coast", "Café 🐉", "NEW_GAME_ROW"); + String request = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + String receipt = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, request, source, 9001L); + + assertThat(WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, WORLD_OPERATION, source)) + .isNotEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, changedWorld)) + .isNotEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, UUID.randomUUID(), request, source, 9001L)) + .isNotEqualTo(receipt); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, request, source, 9002L)) + .isNotEqualTo(receipt); + } + + @Test + void rejectsNilMalformedMismatchedAndRetainedInputs() { + AuthoredWorldSourceEvidence fresh = source("violet-wilds", "A world", "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence retained = source("violet-wilds", "A world", "RETAINED_GAME_V29"); + + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, new UUID(0L, 0L), fresh)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.requestDigest( + "other-namespace", INTAKE_REQUEST, fresh)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, retained)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, "sha256:bad", fresh, 9001L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION, + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, fresh), + fresh, + 0L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredWorldSourceEvidence source( + String worldSlug, String displayName, String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION, TENANT, "north-star", worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION, + SOURCE_OPERATION, + requestDigest, + TENANT, + "north-star", + worldSlug, + displayName, + 42L, + "legacy-game-tenant-42", + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION, + SOURCE_OPERATION, + requestDigest, + TENANT, + "north-star", + worldSlug, + displayName, + 42L, + "legacy-game-tenant-42", + provenanceKind, + evidenceDigest); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java new file mode 100644 index 0000000000..62c5b598c6 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java @@ -0,0 +1,438 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +class WorldAuthoredSourceIntakeGrpcServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, WORLD_SLUG).evidenceDigest(); + + private final WorldAuthoredSourceIntakeService intakeService = + mock(WorldAuthoredSourceIntakeService.class); + private final WorldAuthoredSourceIntakeGrpcService grpcService = + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE); + + @Test + void intakeReturnsOnlyTheExactCommittedReceiptBinding() { + IntakeRequest binding = binding(); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding, 9001L); + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(receipt); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + IntakeAuthoredWorldSourceResponse response = observer.values.get(0); + CommittedReceipt decoded = + WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(binding, response); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding)); + assertThat(response.getReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void readReturnsCommittedReceiptAndEchoesSeparateRequestIdentity() { + IntakeRequest binding = binding(); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding, 9001L); + when(intakeService.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(Optional.of(receipt)); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntake(readRequest(), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + ReadAuthoredWorldSourceIntakeResponse response = observer.values.get(0); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + CommittedReceipt decoded = + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding, READ_REQUEST_ID), response); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding)); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void rejectsUnknownWireFieldsBeforeCallingOwnerService() { + IntakeAuthoredWorldSourceRequest request = + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + RecordingObserver observer = new RecordingObserver<>(); + + grpcService.intakeAuthoredWorldSource(request, observer); + + assertThat(Status.fromThrowable(observer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(intakeService); + + RecordingObserver invalid = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(request, invalid)); + assertThat(Status.fromThrowable(invalid.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(invalid.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongTargetNamespace = + new RecordingObserver<>(); + IntakeAuthoredWorldSourceRequest crossNamespaceRequest = + intakeRequest().toBuilder().setTargetNamespace("other").build(); + withGameDesign( + () -> grpcService.intakeAuthoredWorldSource(crossNamespaceRequest, wrongTargetNamespace)); + assertThat(Status.fromThrowable(wrongTargetNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongTargetNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongWorkload = + new RecordingObserver<>(); + withPeer( + NAMESPACE, + "game-session-service", + () -> grpcService.readAuthoredWorldSourceIntake(readRequest(), wrongWorkload)); + assertThat(Status.fromThrowable(wrongWorkload.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongWorkload.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongNamespace = new RecordingObserver<>(); + withPeer( + "other", + "game-design-service", + () -> grpcService.intakeAuthoredWorldSource(intakeRequest(), wrongNamespace)); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongReadTargetNamespace = + new RecordingObserver<>(); + ReadAuthoredWorldSourceIntakeRequest crossNamespaceReadRequest = + readRequest().toBuilder().setTargetNamespace("other").build(); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntake( + crossNamespaceReadRequest, wrongReadTargetNamespace)); + assertThat(Status.fromThrowable(wrongReadTargetNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongReadTargetNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + } + + @Test + void mapsPeerDenialAndRepositoryConflictToNonSuccessGrpcOutcomes() { + doThrow( + new SecurityException("not the Game Design workload"), + new WorldAuthoredSourceIntakeRepository.RegistrationConflictException("changed source")) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver denied = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), denied)); + assertThat(Status.fromThrowable(denied.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.values).isEmpty(); + + RecordingObserver conflict = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), conflict)); + assertThat(Status.fromThrowable(conflict.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(conflict.values).isEmpty(); + } + + @Test + void preservesTransientStorageFailureAndReportsAbsentReadWithoutReceipt() { + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenThrow(new DataAccessResourceFailureException("database unavailable")); + RecordingObserver unavailable = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), unavailable)); + assertThat(Status.fromThrowable(unavailable.error).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.values).isEmpty(); + + when(intakeService.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(Optional.empty()); + RecordingObserver missing = new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntake(readRequest(), missing)); + assertThat(Status.fromThrowable(missing.error).getCode()).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.values).isEmpty(); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void refusesToReturnAnOwnerReceiptWhoseBindingDoesNotMatch() { + WorldAuthoredSourceIntakeReceipt changed = receipt(binding("other-world"), 9001L); + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(changed); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(Status.fromThrowable(observer.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.values).isEmpty(); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + private static IntakeRequest binding() { + return binding(WORLD_SLUG); + } + + private static IntakeRequest binding(String worldSlug) { + AuthoredWorldSourceEvidence source = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, worldSlug); + return new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + source.evidenceDigest()); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(binding()); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadRequest( + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding(), READ_REQUEST_ID)); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + IntakeRequest binding, long localTenantKey) { + AuthoredWorldSourceEvidence source = + source( + binding.targetNamespace(), + binding.canonicalTenantId(), + binding.sourceOperationId(), + binding.worldSlug()); + if (!binding.expectedSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException("Test source evidence does not match intake binding"); + } + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + binding.targetNamespace(), binding.intakeRequestId(), source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + binding.targetNamespace(), OPERATION_ID, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenantId, UUID sourceOperationId, String worldSlug) { + UUID registrationRequestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registrationRequestId, tenantId, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static void withGameDesign(Runnable action) { + withPeer(NAMESPACE, "game-design-service", action); + } + + private static void withPeer(String namespace, String service, Runnable action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static final class RecordingObserver implements StreamObserver { + private final List values = new ArrayList<>(); + private Throwable error; + private boolean completed; + + @Override + public void onNext(T value) { + values.add(value); + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test recorder retains the exact original throwable solely for assertion.") + public void onError(Throwable throwable) { + error = throwable; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java new file mode 100644 index 0000000000..0e5cb1d834 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java @@ -0,0 +1,695 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; +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.ServerServiceDefinition; +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.NettyChannelBuilder; +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.MetadataUtils; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +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 socket proof with a mocked owner service, not database-to-socket proof. */ +class WorldAuthoredSourceIntakeMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final UUID INTAKE_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID READ_ID = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID WORLD_OPERATION_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final long PRIVATE_WORLD_TENANT_KEY = 987654321L; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static final UnknownFieldSet UNKNOWN_FIELD = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + private static TestPki pki; + + @TempDir Path tempDirectory; + + private Server server; + private WorldAuthoredSourceIntakeService intakeService; + + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final String SOURCE_EVIDENCE_DIGEST = SOURCE_EVIDENCE.evidenceDigest(); + private static final IntakeRequest INTAKE_REQUEST = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + private static final ReadRequest READ_REQUEST = new ReadRequest(INTAKE_REQUEST, READ_ID); + private static final WorldAuthoredSourceIntakeReceipt WORLD_RECEIPT = worldReceipt(); + + @BeforeAll + static void generateFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Fresh World Authored Intake Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-server", WORLD_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-world-server-identity", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-game-design-service", + "spiffe://firemud/ns/other-test/sa/game-design-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "shared-workload-certificate", null)); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void sameNamespaceGameDesignIntakesThenReadsExactReceiptOverSocketMtls() throws Exception { + startServer(pki.worldServer(), null); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "game-design")) { + CommittedReceipt accepted = client.intake(INTAKE_REQUEST); + CommittedReceipt readback = client.read(READ_REQUEST); + + assertPublicReceipt(accepted); + assertPublicReceipt(readback); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_ID, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + } + } + + @Test + void wrongWorkloadsAndWrongNamespaceAreDeniedBeforeDecodeOrOwnerAccess() throws Exception { + startServer(pki.worldServer(), null); + for (TestCertificate wrongCaller : + List.of( + pki.accountClient(), + pki.gameSessionClient(), + pki.worldClient(), + pki.otherNamespaceClient())) { + try (WorldAuthoredSourceIntakeClient client = client(wrongCaller, "caller")) { + assertPermissionDenied(() -> client.intake(INTAKE_REQUEST)); + assertPermissionDenied(() -> client.read(READ_REQUEST)); + } + } + + ManagedChannel malformedCallerChannel = rawMtlsChannel(pki.accountClient()); + try { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(malformedCallerChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + Throwable failure = + catchFailure( + () -> + stub.intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest.getDefaultInstance())); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(malformedCallerChannel); + } + verifyNoInteractions(intakeService); + } + + @Test + void sharedCertificateWithoutWorkloadUriCannotReachOwner() throws Exception { + startServer(pki.worldServer(), null); + try (WorldAuthoredSourceIntakeClient client = + client(pki.noWorkloadUriClient(), "shared-certificate")) { + assertPermissionDenied(() -> client.intake(INTAKE_REQUEST)); + assertPermissionDenied(() -> client.read(READ_REQUEST)); + } + verifyNoInteractions(intakeService); + } + + @Test + void jwtOnlyAndPlaintextCallersFailAtThePhysicalTransportBoundary() throws Exception { + startServer(pki.worldServer(), null); + Metadata jwtOnlyHeaders = new Metadata(); + jwtOnlyHeaders.put(AUTHORIZATION, "Bearer header.payload.signature"); + ManagedChannel noCertificateChannel = rawMtlsChannel(null); + try { + assertTransportFailure( + () -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(noCertificateChannel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(jwtOnlyHeaders)) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + } finally { + stopChannel(noCertificateChannel); + } + + ManagedChannel plaintextChannel = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .usePlaintext() + .build(); + try { + assertTransportFailure( + () -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(plaintextChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + } finally { + stopChannel(plaintextChannel); + } + + CommonGrpcClientProperties plaintext = tlsProperties(pki.gameDesignClient(), "constructor"); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldAuthoredSourceIntakeClient( + endpoints(), + plaintext, + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + verifyNoInteractions(intakeService); + } + + @Test + void clientRejectsAResponseFromTheWrongAuthenticatedWorldServerIdentity() throws Exception { + startServer(pki.wrongWorldServer(), null); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "wrong-server")) { + assertUnauthenticated(() -> client.intake(INTAKE_REQUEST)); + assertUnauthenticated(() -> client.read(READ_REQUEST)); + } + verifyNoInteractions(intakeService); + } + + @Test + void changedEchoDigestAndUnknownFieldsAreRejectedAfterSocketResponse() throws Exception { + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_ECHO)); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "changed-echo")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_DIGEST)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "changed-digest")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.UNKNOWN_FIELDS)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "unknown-fields")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_READ_ID)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "changed-read-id")) { + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake readback"); + } + } + + @Test + void publicWireMessagesNeverContainWorldPrivateNumericTenantKey() { + List messages = + List.of( + IntakeAuthoredWorldSourceRequest.getDescriptor(), + IntakeAuthoredWorldSourceResponse.getDescriptor(), + ReadAuthoredWorldSourceIntakeRequest.getDescriptor(), + ReadAuthoredWorldSourceIntakeResponse.getDescriptor()); + + for (var descriptor : messages) { + assertThat(descriptor.getFields()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "world_tenant_key", "tenant_id"); + } + assertThat(WORLD_RECEIPT.localTenantKey()).isEqualTo(PRIVATE_WORLD_TENANT_KEY); + } + + private void startServer(TestCertificate serverCertificate, ServerInterceptor responseInterceptor) + throws Exception { + intakeService = mock(WorldAuthoredSourceIntakeService.class); + when(intakeService.intake( + eq(1), + eq(NAMESPACE), + eq(INTAKE_ID), + eq(TENANT_ID), + eq("world-one"), + eq(SOURCE_OPERATION_ID), + eq(SOURCE_EVIDENCE_DIGEST))) + .thenReturn(WORLD_RECEIPT); + when(intakeService.readCommittedReceipt( + eq(1), + eq(NAMESPACE), + eq(READ_ID), + eq(INTAKE_ID), + eq(TENANT_ID), + eq("world-one"), + eq(SOURCE_OPERATION_ID), + eq(SOURCE_EVIDENCE_DIGEST))) + .thenReturn(Optional.of(WORLD_RECEIPT)); + + WorldAuthoredSourceIntakeGrpcService handler = + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE); + ServerServiceDefinition intercepted = + ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + if (responseInterceptor != null) { + intercepted = ServerInterceptors.intercept(intercepted, responseInterceptor); + } + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(intercepted) + .build() + .start(); + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private WorldAuthoredSourceIntakeClient client(TestCertificate certificate, String label) + throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + endpoints(), + tlsProperties(certificate, label), + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE); + client.init(); + return client; + } + + private ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = tempDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = tempDirectory.resolve(label + "-client.key"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Path caCertificate = tempDirectory.resolve("test-ca.crt"); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private ManagedChannel rawMtlsChannel(TestCertificate certificate) throws Exception { + var sslBuilder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (certificate != null) { + sslBuilder.keyManager(certificate.privateKey(), certificate.certificate()); + } + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(sslBuilder.build()) + .build(); + } + + private static ServerInterceptor responseMutation(ResponseMutation mutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + Object changed = mutateResponse(message, mutation); + @SuppressWarnings("unchecked") + RespT typedChanged = (RespT) changed; + super.sendMessage(typedChanged); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + private static Object mutateResponse(Object response, ResponseMutation mutation) { + if (response instanceof IntakeAuthoredWorldSourceResponse intake) { + return switch (mutation) { + case CHANGED_ECHO -> intake.toBuilder().setWorldSlug("other-world").build(); + case CHANGED_DIGEST -> + intake.toBuilder().setRequestDigest("sha256:" + "c".repeat(64)).build(); + case UNKNOWN_FIELDS -> intake.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(); + case CHANGED_READ_ID -> intake; + }; + } + if (response instanceof ReadAuthoredWorldSourceIntakeResponse read) { + return switch (mutation) { + case CHANGED_READ_ID -> read.toBuilder().setRequestId(INTAKE_ID.toString()).build(); + case UNKNOWN_FIELDS -> read.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(); + case CHANGED_ECHO, CHANGED_DIGEST -> read; + }; + } + return response; + } + + private static void assertPublicReceipt(CommittedReceipt actual) { + assertThat(actual.schemaVersion()).isEqualTo(1); + assertThat(actual.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(actual.intakeRequestId()).isEqualTo(INTAKE_ID); + assertThat(actual.operationId()).isEqualTo(WORLD_OPERATION_ID); + assertThat(actual.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(actual.worldSlug()).isEqualTo("world-one"); + assertThat(actual.sourceOperationId()).isEqualTo(SOURCE_OPERATION_ID); + assertThat(actual.sourceEvidenceDigest()).isEqualTo(SOURCE_EVIDENCE_DIGEST); + assertThat(actual.requestDigest()).isEqualTo(WORLD_RECEIPT.requestDigest()); + assertThat(actual.receiptDigest()).isEqualTo(WORLD_RECEIPT.receiptDigest()); + } + + private static void assertPermissionDenied(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static void assertUnauthenticated(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + private static void assertTransportFailure(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isNotEqualTo(Status.Code.DEADLINE_EXCEEDED); + } + + private static Throwable catchFailure(Runnable call) { + try { + call.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationId = UUID.fromString("62345678-1234-4234-8234-123456789abc"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT_ID, "tenant-one", "world-one", "World One"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "world-one", + "World One", + 17L, + "source-game-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "world-one", + "World One", + 17L, + "source-game-key", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt worldReceipt() { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_ID, SOURCE_EVIDENCE); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION_ID, + requestDigest, + SOURCE_EVIDENCE, + PRIVATE_WORLD_TENANT_KEY); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + requestDigest, + receiptDigest, + PRIVATE_WORLD_TENANT_KEY, + SOURCE_EVIDENCE); + } + + private static String pem(String type, byte[] bytes) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames)); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private enum ResponseMutation { + CHANGED_ECHO, + CHANGED_DIGEST, + UNKNOWN_FIELDS, + CHANGED_READ_ID + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate wrongWorldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient, + TestCertificate gameSessionClient, + TestCertificate worldClient, + TestCertificate otherNamespaceClient, + TestCertificate noWorkloadUriClient) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java new file mode 100644 index 0000000000..d978161ef6 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -0,0 +1,638 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredSourceIntakeServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String WORLD = "violet-wilds"; + + private final AuthoredWorldSourceClient client = mock(AuthoredWorldSourceClient.class); + private final WorldAuthoredSourceIntakeRepository repository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldAuthoredSourceIntakeService service = + new WorldAuthoredSourceIntakeService(client, repository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactAuthenticatedGameDesignPeerBeforeOwnerAccess() { + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("firemud", "game-session-service"), + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + + verifyNoInteractions(client, repository); + } + + @Test + void validatesAllRequestSelectorsAndDigestBeforeOwnerAccess() { + withGameDesign( + () -> { + assertThatThrownBy( + () -> service.intake(null, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + new UUID(0L, 0L), TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(INTAKE_REQUEST, null, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + INTAKE_REQUEST, new UUID(0L, 0L), WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + INTAKE_REQUEST, TENANT, "Bad-Slug", SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake(INTAKE_REQUEST, TENANT, WORLD, new UUID(0L, 0L), digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, "sha256:bad")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + 2, + NAMESPACE, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + 1, "other", INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(SecurityException.class); + return null; + }); + + verifyNoInteractions(client, repository); + } + + @Test + void deniesWritableAmbientTransactionBeforeReadingOrWriting() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + } + + @Test + void deniesReadOnlyAmbientTransactionBeforeReadingOrWriting() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + } + + @Test + void exactStoredRetryReturnsOriginalReceiptWithoutCallingGameDesign() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + WorldAuthoredSourceIntakeReceipt result = + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + + assertThat(result).isSameAs(receipt); + verify(client, never()).read(any(ReadRequest.class)); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadReturnsWorldReceiptWithoutSourceReadOrAllocation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest())); + + assertThat(result).containsSame(receipt); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadRejectsWrongPeerNamespaceAndChangedReceiptBindingBeforeOwnerAccess() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + "other", + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadReturnsAbsentWithoutMutationWhenNoReceiptExists() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))); + + assertThat(result).isEmpty(); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedRequestScopeOrExpectedDigestConflictsBeforeRemoteReadOrMutation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.of(receipt(source, 9001L))); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + "amber-coast", + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + verify(client, never()).read(any(ReadRequest.class)); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void sourceUnavailableCannotEnterTheOwnerWriteTransaction() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))) + .thenThrow(new IllegalStateException("source unavailable")); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("source unavailable"); + + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedAuthenticatedSourceCannotEnterTheOwnerWriteTransaction() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + AuthoredWorldSourceEvidence[] substitutedSources = { + source("other", TENANT, SOURCE_OPERATION, WORLD), + source( + NAMESPACE, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + SOURCE_OPERATION, + WORLD), + source(NAMESPACE, TENANT, UUID.fromString("77777777-7777-4777-8777-777777777777"), WORLD), + source(NAMESPACE, TENANT, SOURCE_OPERATION, "amber-coast") + }; + for (AuthoredWorldSourceEvidence substituted : substitutedSources) { + when(client.read(any(ReadRequest.class))).thenReturn(substituted); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + substituted.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + } + + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void callerDigestMustMatchFreshAuthenticatedEvidenceBeforeOpeningTransaction() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsFreshSourceBeforeWritableReadCommittedTransactionAndVerifiesFullCommitReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + AtomicInteger readCount = new AtomicInteger(); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return readCount.incrementAndGet() == 1 ? Optional.empty() : Optional.of(receipt); + }); + when(client.read(any(ReadRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return receipt; + }); + + WorldAuthoredSourceIntakeReceipt result = + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + + assertThat(result).isEqualTo(receipt); + assertThat(readCount.get()).isEqualTo(2); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ArgumentCaptor readRequest = ArgumentCaptor.forClass(ReadRequest.class); + verify(client).read(readRequest.capture()); + assertThat(readRequest.getValue().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(readRequest.getValue().requestId()) + .isNotEqualTo(INTAKE_REQUEST) + .isNotEqualTo(new UUID(0L, 0L)); + assertThat(readRequest.getValue().operationId()).isEqualTo(SOURCE_OPERATION); + assertThat(readRequest.getValue().canonicalTenantId()).isEqualTo(TENANT); + assertThat(readRequest.getValue().worldSlug()).isEqualTo(WORLD); + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + } + + @Test + void deniesMissingPostCommitReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty(), Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) + .thenReturn(receipt(source, 9001L)); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after commit readback"); + + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void deniesChangedPostCommitLocalSelectorReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt accepted = receipt(source, 9001L); + WorldAuthoredSourceIntakeReceipt changed = receipt(source, 9002L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changed)); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)).thenReturn(accepted); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("changed during commit readback"); + + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenant, UUID operation, String world) { + UUID registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registration, tenant, "north-star", world, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registration, + operation, + requestDigest, + tenant, + "north-star", + world, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registration, + operation, + requestDigest, + tenant, + "north-star", + world, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + AuthoredWorldSourceEvidence source, long localTenantKey) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + UUID operationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + operationId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, operationId, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameDesign(Supplier action) { + return withPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} From 5ddafa9f780c8ab1f2797130e609e2259e978b24 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:51:42 +1300 Subject: [PATCH 2/3] Use canonical retained provenance in World intake negative fixtures --- .../WorldAuthoredSourceIntakeIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index d764f18544..0466e30488 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -309,7 +309,7 @@ void readBySourceRejectsAnyChangedBindingAndRetainedOrUnmappedEvidence() { .isEmpty(); AuthoredWorldSourceEvidence retainedSource = - source(tenant, tenantSlug, "retained-world", sourceRowId, "Retained", "RETAINED_GAME_V30"); + source(tenant, tenantSlug, "retained-world", sourceRowId, "Retained", "RETAINED_GAME_V29"); assertThat( repository.readBySource( NAMESPACE, @@ -463,7 +463,7 @@ void deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims() { "retained-world", sourceRowId(retainedTenantId), "Retained", - "RETAINED_GAME_V30"); + "RETAINED_GAME_V29"); assertThatThrownBy(() -> accept(UUID.randomUUID(), retainedSource)) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); assertThat(read(requestId)).contains(first); From 2b652bf004b03470ba7446301828ddf5335fd82d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 04:16:51 +1300 Subject: [PATCH 3/3] test(game-design): deterministically corrupt association signature --- ...eSessionTenantAssociationRepositoryIntegrationTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index 3ceb0c0797..90b682d83f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -362,8 +362,11 @@ void applyRequiresOwnerTransactionAndReadRequiresExactCommittedScope() throws Ex assertThatThrownBy(() -> fixture.apply(signed, "another-namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("different namespace"); - Signed malformedSignature = - new Signed(signed.manifest(), signed.ed25519Signature().substring(0, 84) + "AA=="); + byte[] alteredSignatureBytes = Base64.getDecoder().decode(signed.ed25519Signature()); + alteredSignatureBytes[0] ^= 1; + String alteredSignature = Base64.getEncoder().encodeToString(alteredSignatureBytes); + assertThat(alteredSignature).isNotEqualTo(signed.ed25519Signature()); + Signed malformedSignature = new Signed(signed.manifest(), alteredSignature); assertThatThrownBy(() -> fixture.apply(malformedSignature, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("signature");